首页 > 解决方案 > 错误更新变量

问题描述

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

    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 : ");
        }
    }

标签: javavariables

解决方案


我试图在本地运行您的代码,但在那里发现了 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());

推荐阅读