当我尝试运行时出现此错误:
public class gift1 {
public static void main(String[] args) throws IOException{
//declare and initialize scanner to read from gift1.in
Scanner scan = new Scanner(new File("gift1.in"));
//declare and initialize PW to write result
PrintWriter out = new PrintWriter(new File("gift1.out"));
int np = scan.nextInt();
List<String> people = new ArrayList<String>();
for(int o = 1; o<np; o++)
{
people.add(scan.next());
}
Map<String, Integer> monReceived = new HashMap<String, Integer>();
for(String person : people)
{
monReceived.put(person, 0);
}
Map<String, Integer> Initial = new HashMap<String, Integer>();
for(int i = 0; i < np; i++)
{
String person = scan.next();
int amount = scan.nextInt();
int giveto = scan.nextInt();
Initial.put(person, amount);
int amountGift = 0;
if(giveto > 0)
{
amountGift = (amount/giveto);
monReceived.put(person, monReceived.get(person) + (amountGift%giveto));
}
for(int j = 0; j < giveto; j++)
{
String receivers = scan.next();
monReceived.put(receivers, monReceived.get(receivers) + (amountGift - amountGift%giveto));
}
}
for(String person : people)
{
out.println(person + " " + (monReceived.get(person) - Initial.get(person)));
}
out.close();
System.exit(0);
}
}
你知道为什么会这样吗?我需要添加一个try / catch吗?这是我唯一的想法。我考虑过更改和使用BufferedReader,但这会减少我需要的功能。我的代码有什么问题?谢谢,山姆。
更多详情:
它说错误发生在:
at java.util.Scanner.throwFor(Scanner.java:909)
at java.util.Scanner.next(Scanner.java:1530)
at java.util.Scanner.nextInt(Scanner.java:2160)
at java.util.Scanner.nextInt(Scanner.java:2119)
at gift1.main(gift1.java:24)
所以我认为这是与扫描仪有关,但我看不出问题因此我认为我应该尝试尝试/捕获但它没有像我做的那样工作。
编辑:输入数据如下所示:第一行是int,所以我不明白错误。
10
mitnik
Poulsen
Tanner
Stallman
Ritchie
Baran
Spafford
Farmer
Venema
Linus
mitnik
300 3
Poulsen
Tanner
Baran
Poulsen
1000 1
Tanner
Spafford
2000 9
mitnik
Poulsen
Tanner
Stallman
Ritchie
Baran
Farmer
Venema
Linus
Tanner
答案 0 :(得分:0)
您正在阅读的人数10
,但您只处理9
个人。问题是你的循环。您正在从1
迭代到9
(9是最后一个数字<10
)。
你应该从0
开始迭代,所以改变
for(int o = 1; o<np; o++)
到
for(int o = 0; o<np; o++)
否则您将阅读9
人,因此您只会处理
mitnik
Poulsen
Tanner
Stallman
Ritchie
Baran
Spafford
Farmer
将离开
Linus
mitnik
300 3
Poulsen
Tanner
Baran
Poulsen
1000 1
Tanner
.
.
.
所以在你的下一个循环中
String person = scan.next();
int amount = scan.nextInt();
int giveto = scan.nextInt();
String person = scan.next();
将返回Linus
,但int amount = scan.nextInt();
将尝试解析mitnik
,这不是将引发InputMismatchException
的整数。