2017-11-10 90 views
2

我在學生類創建的以下實例變量讀取數據並存儲:故障在一個對象類型實例變量

private String name; 
private char gender;  // 'M'/'F' 
private Date birthday; 
private Preference pref; 
private boolean matched; 

爲偏好I類創建

private int quietTime; // scale of 1-10 private int music; // 1 - 10 private int reading; // 1 - 10 private int chatting; // 1 - 10 爲日期I類創建

private int year; // between 1900 to 3000 private int month; // between 1 to 12, 1 is jan; private int day; // between 1- 31 assume feb max is 28 days!

麻煩是我的主要方法我嘗試導入下面的lib raries

import java.util.Scanner; 
import java.io.File; 

,我想讀txt文件,並存儲數據在每一個學生實例變量,下面是我的代碼我試過,但我收到的錯誤有關 「學生不能被解析爲一個變量」 並且例如下面是從文本文件中的行中的一個:

Abhay F 1-5-1994 0 0 0 0 // seperate by tab and '-'

我給匹配類代碼 - main方法的類:

` 
    Student[] students = new Student[100]; 
    int bestScore = 0; 
    String readInfo = ""; 

    Scanner inFile = new Scanner(new File("Students.txt")).useDelimiter("\t-"); 

    for (int i = 0; i < 100; i++) { 
     readInfo = inFile.next(); 
     student[i] = readInfo; 
    } 
    inFile.close(); 
} 
} 

while(1) { 
    r.nextBoolean(); 
    if (!nextBoolean()) 
    { 
    return true; 
    } 

` 

我剛開始學習java了十天,我完全是一個新手,有人五月幫我如何修正這個錯誤,我真的很appercate它!

+2

那麼,你有一個叫做'student'變量? – shmosel

+1

您需要將字符串轉換成一個Student對象。 Java不會爲你做到這一點。 – Compass

+0

我建議你把問題分解成小塊。在你甚至想到如何閱讀一篇文章之前,你似乎正在嘗試閱讀一份100名學生的名單。從那裏開始。寫一個小方法來讀取代表單個學生的每一段數據。 –

回答

1

如果你想讀或寫的東西到文件,你可以使用這些流。它比Scanner更好。

public static void main(String[] args) throws IOException { 
    BufferedReader reader = new BufferedReader(new FileReader(new File("path\\to\\your\\file.txt"))); 
    BufferedWriter writer = new BufferedWriter(new FileWriter(new File("path\\to\\your\\second\\file.txt"))); 
    //read one line from your file 
    String line = reader.readLine(); 
    //write something to your file 
    writer.write(line); 
} 

如果要將整個對象寫入文件,Java具有ObjectInput/Output流。

public static void main(String[] args) throws IOException, ClassNotFoundException { 
    ObjectInputStream input = new ObjectInputStream(new FileInputStream(new File("yourFile.bin"))); //or any file type 
    ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream(new File("yourFile.bin"))); 

    output.writeObject(yourObject); 
    YourObject yourObject = input.readObject(); 
} 
1

你專門讓這裏的錯誤與您實例名「學生」的數組但你引用名「學生」的數組的事實。

由於您從未實例化學生數組,因此會出現以下錯誤:學生無法解析爲變量。

嘗試:

students[i] = readInfo;