Reputation: 65
I was trying to take string input in java. My input should be like this
3
1,1,[email protected],123 Sesame St.,New York,NY,10011,12345689010
1,2,[email protected],123 Sesame St.,New York,NY,10011,12345689010
1,3,[email protected],123 Sesame St.,New York,NY,10011,12345689010
So, I tried this
Scanner in = new Scanner(System.in);
int TotalNumber = in.nextInt();
String[] Data = new String[TotalNumber];
for (int Counter = 0; Counter < TotalNumber; Counter++) {
Data[Counter] = in.next();
}
in.close();
for (int counter = 0; counter < Data.length; counter++) {
System.out.println(Data[counter]);
}
My output is showing this
1,1,[email protected],123
Sesame
St.,New
What is my problem ? How take input string line properly ?
Update
I found my solution at here Scanner issue when using nextLine after nextXXX
Upvotes: 0
Views: 292
Reputation: 9347
Try this (Mureinik modified code)..
int TotalNumber = in.nextInt();
in.nextLine();
String[] Data = new String[TotalNumber];
for (int Counter = 0; Counter < TotalNumber; Counter++) {
Data[Counter] = in.nextLine();
}
You need a nextLine()
after taking the int
because you will press enter after taking int
and that enter is read by nextLine()
in the Data[0]
.
Upvotes: 0
Reputation: 787
What about:
import java.util.Scanner;
import java.lang.String;
public class Test
{
public static void main(String[] args)
{
char[] sArray;
Scanner scan = new Scanner(System.in);
System.out.print("Enter a Palindrome : ");
String s = scan.nextLine();
s = s.replaceAll("\\s+", "");
sArray = new char[s.length()];
for(int i = 0; i < s.length(); i++)
{
sArray[i] = s.charAt(i);
System.out.print(sArray[i]);
}
}
}
Upvotes: 0
Reputation: 311018
next()
breaks at a whitespace. Instead, you should use nextLine()
to input the entire line to your string:
int TotalNumber = in.nextInt();
String[] Data = new String[TotalNumber];
for (int Counter = 0; Counter < TotalNumber; Counter++) {
Data[Counter] = in.nextLine();
}
Upvotes: 1