Java 使用Scanner类将一行中的每个字符串分配给不同的变量
我对java还相当陌生,我对如何从一个文件中提取一行中的每个字符串,然后使用Scanner在6个不同变量中设置这些值感到有点困惑。这就是我到目前为止所做的:Java 使用Scanner类将一行中的每个字符串分配给不同的变量,java,java.util.scanner,Java,Java.util.scanner,我对java还相当陌生,我对如何从一个文件中提取一行中的每个字符串,然后使用Scanner在6个不同变量中设置这些值感到有点困惑。这就是我到目前为止所做的: File fileName = new File("studentInfo.txt"); Scanner file = new Scanner(fileName); while(file.hasNext()){ String s = file.next(); System.out.println(s); } file.clo
File fileName = new File("studentInfo.txt");
Scanner file = new Scanner(fileName);
while(file.hasNext()){
String s = file.next();
System.out.println(s);
}
file.close();
studentInfo.txt
John Smith 1990 12 25 Junior
Jesse Jane 1993 10 22 Freshman
Jack Ripper 1989 01 14 Senior
我的输出,打印:
John
Smith
1990
12
25
Junior
所以基本上我需要把John设为firstName,Smith设为lastName,1990年设为year,12个月设为month,25个月设为day,初中设为classYear,然后循环下一行,依此类推。有人能帮忙吗?提前感谢。使用一台扫描仪扫描行,每行一台扫描仪读取:
Scanner lineScanner = new Scanner(fileName);
while(file.hasNextLine()){
String line = lineScanner.nextLine();
// parse the line
Scanner sc = new Scanner(line);
String firstName = sc.next();
String lastName = sc.next();
int year = sc.nextInt();
int month = sc.nextInt();
int day = sc.nextInt();
String classYear = sc.next();
sc.close();
// use the variables
// ...
}
file.close();
为什么不考虑用这6个属性创建一个对象对象,然后在循环中设置这些属性呢?我假设在更远处的某个地方,您需要再次访问这些值。如果不知道有多少行,就很难假设n个字符串。