简体   繁体   English

循环退出条件的问题?

[英]issue with exit condition of loop?

I am trying to use a while condition where if a user inputs a string with the first character as number 1, the loop should end. 我正在尝试使用while条件,如果用户输入第一个字符为数字1的字符串,则循环应结束。 However, in my case the loop never ends. 但是,就我而言,循环永远不会结束。 What could I be doing wrong? 我可能做错了什么?

public static void main(String[] args) { 

   ArrayList<Integer> instructions = new ArrayList<Integer>();
    Scanner keyboard = new Scanner(System.in);
    String input = "";
    String termIns = input.substring(0);
   // int termInsInt= Integer.parseInt(termIns);

    do {
        input = keyboard.nextLine();
        int inputInt = Integer.parseInt(input);
        instructions.add(inputInt);
        //String termIns = input.substring(0);

    } while(!termIns.equals("1"));

In addition, what would display the list of all elements in the ArrayList? 另外,什么将显示ArrayList中所有元素的列表?

You need to update termIns with the user input in each iteration of loop: 您需要在每次循环迭代中使用用户输入来更新termIns

do {
        input = keyboard.nextLine();
        int inputInt = Integer.parseInt(input);
        instructions.add(inputInt);
        termIns = input.substring(0);

    } while(!termIns.equals("1"));

Also substring(0) will not help you as 另外substring(0)不能帮助你

substring(int beginIndex) 子串(int beginIndex)

Returns a new string that is a substring of this string. 返回一个新字符串,该字符串是该字符串的子字符串。 The substring begins with the character at the specified index and extends to the end of this string. 子字符串以指定索引处的字符开头,并延伸到该字符串的末尾。

You can use startsWith method instead directly on input as mentioned here 您可以按此处所述直接在输入上使用startsWith方法

while(!input.startsWith("1"))

you're not updating termsIn which is part of your terminating condition. 您没有更新termIn,这是终止条件的一部分。

Also, you can display all the elements in the Arraylist by creating a loop outside of your do-while that prints out all the elements in your arraylist. 另外,您可以通过在do-while之外创建一个循环来显示Arraylist中的所有元素,从而显示出Arraylist中的所有元素。 I'd take a look at the javadoc on Arraylist. 我来看看Arraylist上的javadoc。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM