Java: why is this code not working? Infinite loop?

前端 未结 2 1969
北荒
北荒 2021-01-23 01:08

So as you may be able to tell from my attempt, I\'m trying to figure out how I\'d make a program which gives the user 5 seconds to enter some lines of text, then the Scanner wil

2条回答
  •  -上瘾入骨i
    2021-01-23 01:38

    From the looks of it, this code should work. My only guess is that you are manually entering the input and are forgetting to signal the end of input with CTRL+D. However, doing this, you'll get a NoSuchElementException if you do not use ScanObj.hasNext().

    You could also run your code using input redirection. java OrigClass < data

    A better way to do this would be the following:

    import java.util.Scanner;
    
    public class Sc {
        public static void main(String[] args) {
            Scanner scan = new Scanner(System.in);
            int count = 0;
            String nl; // = scan.nextLine();
            //while (!NL.equals(""))
            while(scan.hasNext())
            {
              count++;
              nl = scan.nextLine();
            }
            System.out.println("Done!  Count: " + count);
            scan.close();
        }
    }
    

    The difference here is that we save the first nextLine() until we're in the while loop. This will give an accurate count of how many lines are in the input.

    Just don't forget to signal end of input with CTRL+D.

提交回复
热议问题