import java.util.*;
class Sept1Little {
public static void main (String args []) {
Scanner s = new Scanner(System.in);
System.out.println("Hey! I'm not gonna program today o.o but I'm gonna do a little program :3");
System.out.println("Let's play with some math!");
System.out.println("Enter two numbers and magic will happen");
System.out.print("Enter the first number: ");
float a = s.nextInt();
System.out.print("Enter the second number: ");
float b = s.nextFloat();
float c = (float) Math.pow( a, b);
System.out.printf("The number is :%f\n" , c);
System.out.println("We love Bernie Sanders!");
System.out.println("Come on, let's push him over the line!");
int poll1 = 30;
System.out.println("Current poll amount: " + poll1);
System.out.println("Let's add 7% and an extra 1%!");
int poll2 = poll1 + 7;
int poll3 = ++poll2;
System.out.println("Bernie Sanders would get :" + poll3 + ". Bernie would get a better percentage than Hillo Clinto-Money");
System.out.println("Write in the best US President Nominee: ");
String president = Keyboard.readString();
if (president.equals("Bernie Sanders")){
System.out.println("You chose Bernie Sanders.");
}
else if (president.equals("Donald Trump")) {
System.out.println("You chose Donald Trump");
}
else if (president.equals("Hillary Clinton")) {
System.out.println("You chose Hillary Clinton ");
}
else {
System.out.println("Choose someone we know...");
}
System.out.println("Let's calculate how much money you owe the govt by... SQUARE ROOTING IT!");
System.out.print("Enter the amount of money you owe the govt: ");
float debt1 = Keyboard.readFloat();
System.out.printf("The amount is now :%f\n" , Math.sqrt(debt1));
System.out.println("Welcome to the Euro to Dollar Convertor!");
System.out.print("Enter the amount in US Dollars you wish to convert to Euro: ");
float euro1 = Keyboard.readFloat();
final float rate = (float) 1.13;
System.out.printf("The amount in Euro is %f\n" , euro1 / rate);
}
}
正如您所看到的,当我要求被提名者时,我正在使用Keyboard.readString();
。当我使用s.readLine();
时,它不起作用,它会跳到else
子句然后崩溃,因为之后需要总统输入float
值。对不起,这有点政治,但我没有打扰它。当我将"Bernie Sanders"
作为"BernieSanders"
时,我没有收到错误,有人知道为什么吗?
答案 0 :(得分:6)
我想这是因为s.nextFloat();
和s.nextInt();
分别只读取float
和int
,而不是整行,因此{{1}的光标它位于float或int之后,而不是在下一行。这是一个例子:
如果您的输入是:
Scanner
你的代码中有:
5 Bench
Prove
为什么它没有捕获a= s.nextInt(); //5
b= s.nextLine(); //" Bench"
值?因为使用Prove
之后s.nextInt()
的光标在Scanner
之后,而不是在下一行(我们拥有5
的行)之后。为了避免这种情况,你必须阅读该行的其余部分(因为你不想要它而对你没用)但没有得到这个值。像这样:
Prove
P.S。:每次使用a= s.nextInt(); //5
s.nextLine(); //We go to the next line
b= s.nextLine(); //"Prove"
或s.nextLine();
作为上面的示例时,您必须使用s.nextInt();
。
我希望它会对你有所帮助!