+ 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]); } } }
7 Respostas
+ 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
0
No the integer to remain in first. And also to be regarded
0
"String arr[]=n.split(" ");" -> "String[] arr=n.split(" ");"
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,
0
Thank you all
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
- 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]);
}
}
}