issue with exit condition of loop?

57 Views Asked by At

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. 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?

2

There are 2 best solutions below

1
On BEST ANSWER

You need to update termIns with the user input in each iteration of loop:

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(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

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

you're not updating termsIn which is part of your terminating condition.

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. I'd take a look at the javadoc on Arraylist.