【问题标题】:bug in do-while loop? [duplicate]do-while循环中的错误? [复制]
【发布时间】:2018-12-07 04:02:07
【问题描述】:

我一直在尝试调试我的代码,但仍然无法弄清楚错误在哪里,请您帮帮我好吗? 该程序将用户输入添加到地图中,直到用户对问题“你想添加更多学生吗?”回答“否”。 但是,无论用户输入“是”还是“否”,程序都会停止运行。 do/while 循环可能有问题,我不确定

 //there is swith statement above and HashMap<String, ArrayList> students = new HashMap()
 case 2:
 ArrayList<Integer> scores = new ArrayList<>();
 String name;
 String answer;
 do {
     System.out.print("Please enter student's name: ");
     name = in.nextLine();
     in.nextLine();
     System.out.print("Please enter " + name + "'s scores: ");
     scores.add(in.nextInt());
     System.out.println("Do you want to add more students yes/no?");
     answer = in.nextLine();
     in.nextLine();
 } while (answer.equals("no"));
 students.put(name, scores); //adding names and scores into HashMap<String, ArrayList> students = new HashMap()

 if (answer.equals("no")) {
     System.out.println("Student Quiz Scores");
     keys.forEach((i) -> {
         System.out.println(i + "'s quiz scores: " + students.get(i));
     });

 }

【问题讨论】:

  • 你有很多电话给nextLine(),但是在你打电话给nextInt()之后你有answer = in.nextLine()。这会将一个空的String 解析为answer,循环条件将变为假,if 将不会输入,程序将结束
  • 我也认为你想要while(!answer.equalsIgnoreCase("no"));

标签: java dictionary arraylist do-while


【解决方案1】:

使用 answer=in.next() 代替 answer=in.nextLine()。

next() = 从此扫描器中查找并返回下一个完整标记。完整标记之前和之后是与分隔符模式匹配的输入。

nextLine() = 将此扫描器前进到当前行并返回被跳过的输入。

【讨论】:

    猜你喜欢
    • 2023-03-18
    • 2016-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-16
    • 1970-01-01
    • 2015-05-30
    • 1970-01-01
    相关资源
    最近更新 更多