如果这太简单了,我道歉,但我现在正在学习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)
答案 0 :(得分:0)
age= scan.nextInt();
if(age==-1){
break;
}
+1学习使用eclipse调试器。