我如何摆脱这个用户说是的无限循环,然后回到第一个 while 循环,直到用户说不?

我试图提示用户输入一个数字,然后询问他们是否要输入另一个数字。如果是,则他们重新启动第一个 while 循环,如果不是,则他们退出以打印他们选择的数字。


但是似乎无论我做什么,我都无法摆脱第一个循环。它只是一遍又一遍地重复数字。


我试着把 userInput = "y", break, and continue 放在 where valid= true; 的末尾 目前是,它们都产生相同的结果。


陷入无限循环。


ArrayList<Integer> inputs = new ArrayList<Integer>();

System.out.println("Enter some numbers: ");


   String userInput = "y"; 

    boolean valid = false;


    do {

        while (scnr.hasNextInt()) {

           inputs.add(scnr.nextInt());

           System.out.println("Would you like to enter another?");

           valid = true;

           }

           System.out.println(inputs);


    } while (!userInput.equalsIgnoreCase("n"));


慕勒3428872
浏览 90回答 2
2回答

料青山看我应如是

问题是你没有跳出内循环。在这里我将如何编写相同的代码:import java.util.ArrayList;import java.util.Scanner;public class ReadNumbers {&nbsp; public static void main(String[] args) {&nbsp; &nbsp; ArrayList<Integer> inputs = new ArrayList<Integer>();&nbsp; &nbsp; System.out.println("Enter some numbers: ");&nbsp; &nbsp; try (Scanner scnr = new Scanner(System.in)) {&nbsp; &nbsp; &nbsp; do {&nbsp; &nbsp; &nbsp; &nbsp; inputs.add(scnr.nextInt());&nbsp; &nbsp; &nbsp; &nbsp; System.out.println("Would you like to enter another y/n?");&nbsp; &nbsp; &nbsp; } while (scnr.next().equalsIgnoreCase("y"));&nbsp; &nbsp; }&nbsp; &nbsp; System.out.println(inputs);&nbsp; }}这会产生以下输出:Enter some numbers:&nbsp;14Would you like to enter another y/n?y15Would you like to enter another y/n?y17Would you like to enter another y/n?y44Would you like to enter another y/n?n[14, 15, 17, 44]读取数字的另一种方法是从空格分隔的行中读取几个:

慕姐4208626

我认为你把这个复杂化了。您只需要一个循环,该循环一直运行到用户输入“n”为止。在此之前,要求用户输入一个数字,读入,然后询问他们是否要继续。适当地更新循环条件,你就完成了:public static void main(String... args) {&nbsp; &nbsp; ArrayList<Integer> inputs = new ArrayList<Integer>();&nbsp; &nbsp; try (Scanner scnr = new Scanner(System.in)) {&nbsp; &nbsp; &nbsp; &nbsp; boolean valid = true;&nbsp; &nbsp; &nbsp; &nbsp; while (valid) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println("Enter some numbers: ");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (scnr.hasNextInt()) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; inputs.add(scnr.nextInt());&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println("Would you like to enter another?");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; String response = scnr.next();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; valid = response.trim().equalsIgnoreCase("y");&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; System.out.println(inputs);}产生输出Enter some numbers:&nbsp;1Would you like to enter another?yEnter some numbers:&nbsp;2Would you like to enter another?yEnter some numbers:&nbsp;3Would you like to enter another?n[1, 2, 3]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java