首页 > 解决方案 > 首先,如果条件不能正常工作

问题描述

当我运行我的代码时,它工作正常,直到它到达我的 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();
    }

  }
}
 

标签: java

解决方案


我看到你编辑了你的答案,这很好,因为那里的逻辑是错误的。您应该先检查输入是 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();如果仍然有错误只是评论附近。我很乐意提供帮助


推荐阅读