我试图在java中获取字符串输入。我的输入应该是这样的
3
1,1,bugs@bunny.com,123 Sesame St.,New York,NY,10011,12345689010
1,2,bugs@bunny.com,123 Sesame St.,New York,NY,10011,12345689010
1,3,bugs@bunny.com,123 Sesame St.,New York,NY,10011,12345689010
所以,我试过这个
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]);
}
我的输出显示了这个
1,1,bugs@bunny.com,123
Sesame
St.,New
我的问题是什么?如何正确输入字符串?
更新
找到了我的解决方案答案 0 :(得分:1)
next()
在空白处打破。相反,您应该使用nextLine()
将整行输入到字符串中:
int TotalNumber = in.nextInt();
String[] Data = new String[TotalNumber];
for (int Counter = 0; Counter < TotalNumber; Counter++) {
Data[Counter] = in.nextLine();
}
答案 1 :(得分:0)
尝试使用Data[Counter] = in.nextLine();
答案 2 :(得分:0)
怎么样:
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]);
}
}
}
答案 3 :(得分:0)
试试这个(Mureinik修改过的代码)..
int TotalNumber = in.nextInt();
in.nextLine();
String[] Data = new String[TotalNumber];
for (int Counter = 0; Counter < TotalNumber; Counter++) {
Data[Counter] = in.nextLine();
}
您在获取nextLine()
后需要int
,因为您在执行int
后会按Enter键,并且nextLine()
中的Data[0]
会读取该输入。