【问题标题】:Errorin update variable [closed]更新变量中的错误[关闭]
【发布时间】:2021-06-15 09:37:25
【问题描述】:

我想更新我的变量,我的代码有一个错误,我不知道哪里有错误

    String name = " "; 
    String family = " "; 
    int age = 0;
    Scanner input = new Scanner(System.in);


    int choise;
    while (true){
        System.out.println("1:Name  2:Family  3:Age ---- 0:Exit");
        choise = input.nextInt();
        if (choise == 0) break;
        else if (choise == 1){
            System.out.println("Please enter the name : ");
            name = input.nextLine();
        }
        else if (choise == 2){
            System.out.println("Please enter the family : ");
            family = input.nextLine();
        }
        else if (choise == 3){
            System.out.println("Please enter the age : ");
        }
    }

【问题讨论】:

  • 错误是什么?
  • "我不知道哪里有错误" - 我们也不知道,因为我们不知道您的代码应该做什么,即您期望什么,并且它正在做什么。
  • 您到底想做什么?预期的行为是什么?
  • 错误是:在 java.util.Scanner.throwFor(Scanner.java:864) 在 java.util.Scanner.next(Scanner.java) 的线程 "main" java.util.InputMismatchException 中的异常:1485) 在 java.util.Scanner.nextInt(Scanner.java:2117) 在 java.util.Scanner.nextInt(Scanner.java:2076) 在 Code_4.main(Code_4.java:14) @tomerpacific

标签: java variables


【解决方案1】:

我试图在本地运行您的代码,但在那里发现了 2 个问题:

  1. 当应用程序尝试在 if-else 部分等待输入时,它不是在等待,而是循环到下一次迭代。
  1. 与第 1 项相关,根据结果,应用程序应等待输入名称。在我输入我的名字后,它抛出了一个错误。为什么?显然,应用程序不是等待名称,而是选择。

这里清楚地描述了这个问题: Java Scanner doesn't wait for user input

问题是 nextInt() 不消耗 '\n',所以下一次调用 nextLine() 消耗它,然后等待读取 y 的输入

我的建议是将 nextInt() 更改为 nextLine() 然后手动转换为 int

choise = Integer.parseInt(input.nextLine());

【讨论】:

  • @jhamon ya,感谢您的纠正。更新我的回答,将我的建议添加到 OP。
【解决方案2】:

我将代码更改为此,它现在正在工作。但是我应该在 name = input.nexline() 或 .. 之后写 input.nexline() 或 input.nexint() 吗?

 String name = " "; String family = " "; int age = 0;
    Scanner input = new Scanner(System.in);


    int choise;
    while (true){
        System.out.println("1:Name  2:Family  3:Age ---- 0:Exit");
        choise = input.nextInt();
        if (choise == 0) break;
        else if (choise == 1){
            System.out.println("Please enter the name : ");
            name = input.nextLine();
            input.nextLine();
        }
        else if (choise == 2){
            System.out.println("Please enter the family : ");
            family = input.nextLine();
            input.nextLine();
        }
        else if (choise == 3){
            System.out.println("Please enter the age : ");
            age = input.nextInt();
            input.nextInt();
        }
    }

【讨论】:

    猜你喜欢
    • 2021-10-06
    • 1970-01-01
    • 1970-01-01
    • 2016-03-31
    • 2017-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多