0

I'm attempting to take a user inputted phrase that is greater than one line and turn it into one string. I guess I'm confused by how hasNext() works because I thought it would return as false if there was blank space. How can I fix my while loop so that it breaks once it reaches the end of the phase? Or how can I achieve this in general?

public static void main(String[] args) {
        Scanner scan=new Scanner(System.in);
        String text="";
        String s="";
        while(scan.hasNext()){

            s=scan.nextLine();
            text+=s;
            System.out.println(text);

        }

  • You can use a sentinel value, such as an empty line, something like `if (s.trim().isEmpty() { break; }`. Otherwise the while loop will continually sit and wait for the next input. In Windows Ctrl-c might work to break out by itself. – DontKnowMuchBut Getting Better May 11 '20 at 02:25
  • 1
    what is the 'end' of phrase ...that is your condition to break out of loop. – Peeyush May 11 '20 at 02:25
  • In other words, the input doesn't know if there's a next line in the stream, so it just keeps reading to find one. Hence, infinite loop. To stop this you have to close standard input (possible on some systems with control-D or control-C). – markspace May 11 '20 at 02:32

0 Answers0