java - 首先,如果条件不能正常工作
问题描述
当我运行我的代码时,它工作正常,直到它到达我的 if 语句评估答案字符串的地步。无论我在扫描仪对象中输入什么,它都会运行第一个 if 语句。如果我取出scanner.nextLine(); 那么它不会让我为答案对象输入任何输入。
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();
}
}
}
解决方案
我看到你编辑了你的答案,这很好,因为那里的逻辑是错误的。您应该先检查输入是 Y 还是 N,然后再验证它不在两者中。您的问题很简单,这是有关扫描仪类的常见问题。只需添加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();
if (answer.equals("Y")) {
System.out.println("Your a good person.");
} else if (answer.equals("N")) {
System.out.println("Have a nice day.");
} else {
throw new NumberFormatException();
}
} catch (NumberFormatException e) {
System.out.println(e.getMessage());
}
每当扫描仪在您的情况下出现问题时添加字符串垃圾,answer=scanner.nextLine();
如果仍然有错误只是评论附近。我很乐意提供帮助
推荐阅读
- amazon-web-services - 使用控制台和 CLI 时 S3 存储桶大小不同
- c++ - “if (argc < 2 || argc > 2)” 是否可以使用 2 个参数?& 在抛出“std::out_of_range”错误实例后调用终止
- sql - 按列的值对列进行排序
- regex - 使用正则表达式查找不包含字符串的文本块
- scala - regex check and proceed next call
- ubuntu - 如何从虚拟环境中将我的 jupyter 笔记本作为服务运行
- pip - 即使成功安装了pyramid-arima,也无法导入
- apache-kafka - 尝试使用Kafka将数据从服务器A发送到服务器B
- c++ - 如何解释嵌套的继承类结构?
- spring - 如何在本地重现“java.sql.SQLRecoverableException: Closed Connection”错误?