Home > Net >  java How to read 2 different datatypes in one line using a Scanner
java How to read 2 different datatypes in one line using a Scanner

Time:12-03

i need to use a Scanner where the first word is a string an the second a double for e.x. "Drive 5" but both need to be written onto the same line in the scanner

Scanner scanner = new Scanner(System.in); String befehl = scanner.nextLine(); double wert = scanner.nextDouble();

CodePudding user response:

Use Scanner#next and then Scanner#nextDouble.

String befehl = scanner.next();
double wert = scanner.nextDouble();

CodePudding user response:

Sometimes I think people miss the point and power of Scanner.

Use your first Scanner to read the next line of input from the user, then use another Scanner to perform the parsing/validation of that input, independently.

This has the added benefit of ensuring that the input Scanner is kept clean and up-to-date (and avoids all those "my scanner is skipping input" questions

  •  Tags:  
  • java
  • Related