gpt4 book ai didi

java - 在比较字符串时,在 Java 中将 if 与 Scanner 结合使用无法正常工作

转载 作者:行者123 更新时间:2023-11-29 06:57:09 25 4
gpt4 key购买 nike

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" 时,我没有收到错误消息,有人知道为什么吗?

最佳答案

我猜这是因为 s.nextFloat();s.nextInt(); 只读取 floatint,而不是整行,所以 Scanner 的光标在 float 或 int 之后,而不是在下一行。这里有一个例子:

如果您的输入是:

5 Bench
Prove

你的代码中有:

a= s.nextInt(); //5
b= s.nextLine(); //" Bench"

为什么它没有捕捉到 Prove 值?因为在使用 s.nextInt() 之后,Scanner 的光标在 5 之后,而不是在下一行(我们在其中的行)有证明)。为避免它,您必须阅读该行的其余部分(对您无用,因为您不想要它)但没有获得此值。像这样:

a= s.nextInt(); //5
s.nextLine(); //We go to the next line
b= s.nextLine(); //"Prove"

附注:每次使用 s.nextInt(); 时都必须使用 s.nextLine(); >s.nextFloat(); 作为我上面的例子。

希望对您有所帮助!

关于java - 在比较字符串时,在 Java 中将 if 与 Scanner 结合使用无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32361758/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com