+ 2

Can anyone tell me why it shows no output?

import java.util.*; public class Program { public static void main(String[] args) { Scanner sc=new Scanner (System.in); int a=sc.nextInt(); String n=sc.nextLine(); String arr[]=n.split(" "); for(int i=0;i<arr.length;i++) { System.out.println (arr[i]); } } }

20th Jul 2021, 5:17 PM
Atul [Inactive]
7 Answers
+ 1
After nextInt, there's still something in the buffer, so you need to call sc.nextLine() to clear. Then you can read the string input. https://stackoverflow.com/questions/19485407/user-input-string-and-integers-in-java#19485423
20th Jul 2021, 5:58 PM
Lisa
Lisa - avatar
0
No the integer to remain in first. And also to be regarded
20th Jul 2021, 5:27 PM
Atul [Inactive]
0
"String arr[]=n.split(" ");" -> "String[] arr=n.split(" ");"
20th Jul 2021, 5:32 PM
Flash
0
this should solve it: import java.util.*; public class Program { public static void main(String[] args) { Scanner sc = new Scanner (System.in); int a = sc.nextInt(); sc.nextLine(); String n = sc.nextLine(); sc.close(); String[] arr = n.split(" "); for (int i=0;i<arr.length;i++) { System.out.println (arr[i]); } } } https://stackoverflow.com/questions/32948425/how-to-read-int-double-and-sentence-of-string-using-same-scanner-variable NB. you still have a syntax error in that post,
20th Jul 2021, 5:54 PM
Flash
0
Thank you all
20th Jul 2021, 6:01 PM
Atul [Inactive]
0
1\n 1 2 3\n nextInt() reads num after num is space or \n char for end of line (depends of input way) next() reads everything to the \n everything after is ignored so arr then can be empty (depends of input way) because first \n was read now
20th Jul 2021, 7:12 PM
zemiak
- 1
import java.util.*; public class Program { public static void main(String[] args) { Scanner sc=new Scanner (System.in); String n= sc.nextLine(); String[] arr=n.split(" "); for(int i=0;i<arr.length;i++) { System.out.println (arr[i]); } } }
20th Jul 2021, 5:22 PM
Flash