我一直在尝试为我的功课做这个问题,而对于我的一生,我无法弄清楚。问题是:编写一个程序,读取“worked_example_1/babynames.txt”并生成两个文件,boynames.txt 和 girlnames.txt,将男孩和女孩的数据分开。
这是来自 wiley.com/go/javaexamples 的 Worked Example 11 中针对此问题的代码:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class BabyNames
{
public static final double LIMIT = 50;
public static void main(String[] args) throws FileNotFoundException
{
Scanner in = new Scanner(new File("babynames.txt"));
RecordReader boys = new RecordReader(LIMIT);
RecordReader girls = new RecordReader(LIMIT);
while (boys.hasMore() || girls.hasMore())
{
int rank = in.nextInt();
System.out.print(rank + " ");
boys.process(in);
girls.process(in);
System.out.println();
}
in.close();
}
}
和这个:
import java.util.Scanner;
public class RecordReader
{
private double total;
private double limit;
public RecordReader(double aLimit)
{
total = 0;
limit = aLimit;
}
public void process(Scanner in)
{
String name = in.next();
int count = in.nextInt();
double percent = in.nextDouble();
if (total < limit)
{
System.out.print(name + " ");
}
total = total + percent;
}
public boolean hasMore()
{
return total < limit;
}
}
我创建了 babynames.txt 并将其放在与 .java 文件相同的 src 文件夹中,如果我给出文件的直接路径,它会出现文件未找到
Scanner in = new Scanner(new File("C:/Users/me/SkyDrive/Schoolwork/CIS150AB/Chapter 11.1/src/babynames.txt"));
它找到了文件,但给了我这个错误:
Exception in thread "main" java.util.InputMismatchException
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 BabyNames.main(BabyNames.java:20)
在我看来,这个错误是因为第 20 行 int rank = in.nextInt(); 并且它在寻找一个 int 时寻找一个字符串,但这直接来自 Wiley 网站,所以我不确定。
对此的任何帮助将不胜感激,显然我不适合 Java 在线课程。一旦有一个适合我的日程安排的课程,我将在学校上课。