When to use different types of scanner lines in Java | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

When to use different types of scanner lines in Java

Hello, Please take a look at the code below. Ex. Line 1: Scanner scanner = new Scanner(System.in); Line 2: // System.out.println(scanner.nextLine()); Lines 3 - 4: int days = scanner.nextInt(); System.out.println(days); Lines 5 - 6: //days = scanner.nextInt(); System.out.println(days*24); First I set up the scanner, then I can add lines 3, 4 and 6, but if I add line 2 or line 5 I will get Exceptions, and I would like to know why that is not allowed. Thank you in advance, Iulia

29th Aug 2022, 5:46 PM
Iulia
2 Answers
+ 1
All lines are valid. They raise exception when you don't provide any corresponding input when the lines expecting inputs.. Line 2: accept a line of string. Line 3: expects a integer input Line 5: also accepts an integer input. so only If the input is not available or mismatch of inputs then it raise exceptions...
29th Aug 2022, 5:57 PM
Jayakrishna 🇮🇳
+ 1
Dear @Ę ~ J and @Jayakrishna🇮🇳, So if I want the scanner to take an input more than once in the program, how can I do that? Like how would I do it if I wanted to have the same type of input more than once (but the user could put in a different input (of the same type) each time)? And how can I make it so that I can take in more than one type of input, like Strings and ints? In that case know I would have to make one scanner for each type of input, but I don't know how I would do that. Thanks, Iulia
29th Aug 2022, 6:30 PM
Iulia