当我运行代码时,它工作正常,直到if语句计算出答案字符串为止。不管我在scanner对象中输入什么,它总是运行第一个if语句。如果我拿出扫描仪。nextline();然后它将不允许我为answer对象输入任何输入。
public class ExceptionTest {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
boolean statement = true;
int total;
String answer = null;
do{
try{
System.out.println("Please enter the amount of Trees:");
int trees = scanner.nextInt();
if(trees < 0){
throw new InvalidNumberException();
}
System.out.printf("Amount of fruit produced is: %d%n", trees * 10);
System.out.println("Please enter the amount of people to feed: ");
int people = scanner.nextInt();
scanner.nextLine();
total = trees * 10 - people * 2;
System.out.printf("The amount of fruit left over is: %d%n", total);
statement = false;
}
catch(InvalidNumberException e){
System.out.println(e.getMessage());
scanner.nextLine();}
}
while(statement);
System.out.println("Would you like to donate the rest of the fruit? Y or N:");
try{
answer = scanner.nextLine();
if(answer == "Y"){
System.out.println("Your a good person.");
}else if(answer == "N"){
System.out.println("Have a nice day.");
}else {
throw new NumberFormatException();
}
}
catch(NumberFormatException e){
System.out.println(e.getMessage());
scanner.nextLine();
}
}
}
2条答案
按热度按时间4uqofj5v1#
这里有三件事:
第一次打电话给
scanner.nextLine()
获取用户输入,但未存储在变量中。这个answer
变量正在存储对的第二个不必要的调用scanner.nextLine()
. 编辑原因scanner.nextLine()
需要的是上一个扫描仪调用的是scanner.nextInt()
.nextInt()
不将光标移到下一行。请参阅:在使用next()或nextfoo()之后,扫描仪正在跳过nextline()?。你无法比较
Object
正在使用==
以及!=
. java的比较运算符测试严格的对象相等性。你不是要检查它们是否相同String
示例,您的意思是检查两个示例是否存储相同的文本。正确的比较是!answer.equals("Y")
.想想if语句的逻辑。想想这是怎么回事
||
操作员的意思是。woobm2wo2#
我看到你编辑了你的答案,这是好的,因为逻辑是错误的。您应该先检查输入是y还是n,然后再验证它不在这两个字段中。您的问题非常简单,这是有关scanner类的常见问题。只需添加
String trash = scanner.nextLine();
去除许多不必要的scanner.nextLine();
```String trash = scanner.nextLine();
System.out.println("Would you like to donate the rest of the fruit? Y or N:");
try {
answer = scanner.nextLine();