Reputation: 11
i want to input a String like america south korea japan
and want to store it in array. I am able to do it for countries having one word name but for text having more than one word eg how can i add south korea nextLine() is not working i did this.
String c=new String[2];
for(int i=0;i<3;i++)
{
c=sc.next(); //taking one word
//tried sc.nextLine() also;
}
Upvotes: 1
Views: 102
Reputation: 201
Try this:
String c= null;
c=sc.nextLine();
String[] split = c.split(" ");
for(String x : split)
System.out.println(x);
Output :
america south korea japan
america
south
korea
japan
You are assigning an string array to string variable.
String c = new String[2]; is wrong initialization
String[] c = new String[2]; is proper initialization
If you want to try with array Try this code :
Scanner sc = new Scanner(System.in);
String[] c= new String[3];
for(int i=0;i<3;i++) {
c[i]=sc.nextLine();
}
for(String x : c)
System.out.println(x);
}
Output :
america
South Korea
Japan
america
South Korea
Japan
Upvotes: 1