简体   繁体   中英

Scanner not actually taking in user input

I've tried different uses for Scanners (I want it to read in Files but I also tried just Strings), and it just skips over the code as if it doesn't exist. No error messages are shown.

   public static void main(String[] args)
      throws FileNotFoundException {
      
      Scanner test = new Scanner(System.in);
      String testLine = test.next();

      Scanner input = new Scanner(new File("data.txt"));

      while(input.hasNextLine){
         String name = input.nextLine();
         String letters = input.nextLine();
         System.out.println(name + ": " + letters);
      }
   }

Your code doesn't compile, because hasNextLine() is a function, not a class member.

You are actually reading from System.in at test.next(); - you have to enter some text, then your code will continue to run. It's just waiting for a user input - thus no exception is thrown.

At this line of code:

String testLine = test.next();

your program is waiting for your input. It cannot proceed to next line till you provide an input.

EDIT:
Taking cue from Charlie's comment below, here is a quote about System.in fromdocs.

The "standard" input stream. This stream is already open and ready to supply input data. Typically this stream corresponds to keyboard input or another input source specified by the host environment or user.

More here. .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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