-2
如果這太簡單了,我很抱歉,但我現在正在學習Java,並且卡住了。我目前正在進行在線學校教育,並陷入了一個涉及數據分析的問題。我創建了這段代碼的文件:從java中的文件中讀取數據時出現問題
import java.util.Scanner;
import java.io.*;
class PrintnumbertoFile
{
public static void main (String[] args) throws IOException
{
Scanner scan = new Scanner(System.in);
int age=0, IQ, Gender, height;
File file = new File("data.txt");
PrintStream print = new PrintStream(file);
while (age !=-1)
{
System.out.print("Age(-1 to exit): ");
age= scan.nextInt();
print.println(age);
System.out.print("IQ: ");
IQ= scan.nextInt();
print.println(IQ);
System.out.print("Gender(1 for male, 0 for female): ");
Gender= scan.nextInt();
print.println(Gender);
System.out.print("Height (Inches): ");
height= scan.nextInt();
print.println(height);
}
print.close();
}
}
這裏得到了輸入的數據:
17
120
1
71
20
183
0
63
15
100
1
61
31
165
0
73
20
190
1
62
50
167
0
59
36
295
0
79
76
173
1
58
12
97
1
48
27
115
0
72
-1
雖然本身進入-1黯然後不關閉數據。但這不是問題。問題是,當我讀到這段代碼的數據:
import java.util.Scanner;
import java.io.*;
class getnumbersfromFile
{
public static void main (String[] args) throws IOException
{
File file = new File("data.txt");
Scanner scan = new Scanner(file);
int age=0, IQ, Gender, height, AmountOfPeople = 0;
while (age != -1)
{
System.out.print("Age(-1 to exit): ");
age= scan.nextInt();
System.out.println(age);
System.out.print("IQ: ");
IQ= scan.nextInt();
System.out.println(IQ);
System.out.print("Gender(1 for male, 0 for female): ");
Gender= scan.nextInt();
System.out.println(Gender);
AmountOfPeople++;
System.out.print("Height (Inches): ");
height= scan.nextInt();
System.out.println(height);
}
scan.close();
System.out.println("Number of people in the file: " +AmountOfPeople);
}
}
我總是在最後得到一個錯誤,因爲它不讀書-1後停止。我也試過了:
while (scan.hasNextInt())
in,但是也沒有做任何事。我再次道歉,如果這看起來真的很愚蠢,但我主要是遵循老師給我的指導,並沒有幫助。我也不能要求老師幫忙,因爲他在夏天不工作。任何幫助,將不勝感激!
P.S.如果有人知道如何讓最老的和最年輕的人離開檔案,那麼這也會非常有用!
編輯:哎呀,對不起。我忘了添加錯誤代碼。這就是我不斷收到:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at getnumbersfromFile.main(getnumbersfromFile.java:17)
「_I總是得到一個錯誤_」什麼錯誤?另外,保持你的命名約定一致的意思是以小寫字母開始你所有的變量。 – csmckelvey 2014-08-30 22:23:21
問題是,即使在讀取-1之後,仍然嘗試讀取其餘的變量(不存在)。你需要退出循環,比如'return',而不是繼續。此外,您應該使用'try'塊或'try'-with-resources關閉掃描器,而不是在拋出異常時跳過它。最後,學會使用調試器;通過循環進行操作會向您顯示問題的實際情況。 – chrylis 2014-08-30 22:34:00