大家好我有一个扫描仪,它从文件读取输入,它读取不正确。
我在文本文件中有多个记录/行数据,我想要读取它们并将它们分配到变量中,代码我一次读取所有记录而不是单独读取。如何让它逐行读取并分配每一行。错误是在String name = inFile.next()它读取文件中的所有内容而不仅仅是名称,我尝试了String name = inFile.nextLine(),当我这样做时它会抛出异常。
这是我的代码
import java.util.*;
import java.io.*;
public class setupProgram
{
public static void main(String [] args)
{
Scanner inFile = null; // creates the Scanner class object
File file = new File("students.dat");
try
{
inFile= new Scanner(file); //Creates Scanner object and and the file Reader
int quantity; // Stores the quanity of records
quantity = inFile.nextInt(); // read the first line telling us how many students they are.
System.out.println(quantity);
for(int i = 0; i < quantity; i++)// This loop reads information as long as there is information
{
for(int a = 0; a < 8; a++)// This loop reads the code in 7's cause the records are in 7s
{
String name =inFile.next(); // The error is here in the sense that this line reads all the information in the file not its own line
int Idnum = inFile.nextInt();
int code = inFile.nextInt();
String unit1 = inFile.next();
String unit2 = inFile.next();
String unit3 = inFile.next();
String unit4 = inFile.next();
if(name !=null && Idnum !=0 && code !=0 && unit1 !=null && unit2 !=null && unit3 !=null && unit4 !=null)
{
students1 s1 = new students1();
s1.student(name,Idnum,code,unit1,unit2,u...
students.add(s1);
}
System.out.println(name);
System.out.println("1"+Idnum);
System.out.println("2"+code);
System.out.println(unit1);
System.out.println(unit2);
System.out.println(unit3);
System.out.println(unit4);
}
}
}
catch(Exception a)
{
//a.printStackTrace();
System.out.println("The file was not read");
}
finally
{
try
{
inFile.close();
}
catch(Exception b)
{
System.out.println("The file couldnt read");
}
}
}
这是文件,我尝试过quantity = inFile.nextLine();这不起作用
4 莎莉史密斯 10101010 1 FIT3280 FIT3230 FIT3260 FIT3290 布莱恩道斯 12341234 1 FIT3230 FIT3240 FIT3260 FIT3250 费飞林 15151515 13 FIT3230 FIT3250 FIT3290 FIT3240 Janelle Patten 13579999 18 FIT3230 FIT3250 FIT3260 FIT3280