0

What's wrong with this version of this code? (I read something about an "incorrect exit condition" but I don't see how that could be?)

import java.util.*;

public class First {

    public static void main(String[] args) {

        ArrayList<String> lineOne = new ArrayList<String>();

        Scanner scan = new Scanner(System.in);

        while(scan.hasNext()){
              String lineOneVar = scan.next();
              lineOne.add(lineOneVar);
              /*System.out.println(lineOneVar);
              System.out.println(lineOne);
              System.out.println(lineOne.get(0));*/
        }

        System.out.println(lineOne);
        //Does not produce an output.
    }
}
Moon
  • 2,837
  • 1
  • 20
  • 34
  • scan.hasNext(). do you think that returns true? Have you debugged to check? or, just add some print statements in that loop to verify – Stultuske May 04 '20 at 06:06
  • @Stultuske it does work, the print statements that I commented do print both arrays and indexes as expected – MathNovice May 04 '20 at 06:13
  • 1
    that should give you some insight. You never break out of the while loop. – Stultuske May 04 '20 at 06:21

1 Answers1

1

You should use the below concept

if(s1.equals("exit")) {
        break;
}

Please see this solution

  • 1
    if you want to flag a question as a duplicate, you should do that, not post it as an answer. what you posted is a copy-paste ready solution, not a 'concept'. Adding information about why it should be added would be advised – Stultuske May 04 '20 at 06:29
  • Works. Thank you – MathNovice May 04 '20 at 06:31