gpt4 book ai didi

Java初学者: Message coming up under General output in java although process was completed

转载 作者:行者123 更新时间:2023-11-30 04:01:04 26 4
gpt4 key购买 nike

我写了一个程序来显示猜出 jar 里弹珠数量最接近的人的 ID 号。这是程序:

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;

public class SuperMarbles
{
public static void main(String[] args) throws IOException
{
int guess = 0;
int contestants = 0;
int num_marbles, answer, id, winner = 0;

Scanner scanner = new Scanner(new FileReader("promo.txt"));
PrintWriter printWriter = new PrintWriter(new FileWriter("winner.txt"));

num_marbles = scanner.nextInt();
id = scanner.nextInt();
while (id != 0)
{
answer = scanner.nextInt();
if (answer > guess && answer <= num_marbles)
{
guess = answer;
winner = id;
id = scanner.nextInt();
contestants++;
}
}

if (guess == 0)
{
printWriter.printf("There are %d contestants", contestants);
printWriter.printf("\nThere are no winners");
}
else
{
printWriter.printf("There are %d contestants", contestants);
printWriter.printf("\nThe winner is ID#%d", winner);
}
scanner.close();
printWriter.close();

}

}

这是输入文件“promo.txt”中的数据:
258
0001 200
0002 198
0003 430
0004 12
0005 30
0006 45
0007 154
0008 250
0009 120
0

现在,我使用 JCreator,当我尝试编译时,在“构建输出”下,我没有收到任何错误并且“进程已完成”,但在“常规输出”下,这就是我得到的:

Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:907)
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 SuperMarbles.main(SuperMarbles.java:25)

Process completed.

此外,未创建输出文件“winner.txt”。对于 java,我是个新手,但任何帮助将不胜感激。

最佳答案

我已在您的代码中添加了一些调试功能。看看它向我们展示了什么:

...

num_marbles = in.nextInt();
System.out.println("num_marbles=" + num_marbles);
id = in.nextInt();
System.out.println("id=" + id);
while (id!=0) {
answer = in.nextInt();
System.out.println("answer=" + answer);

...

输出:

[C:\java_code\]java SuperMarbles
num_marbles=258
id=1
answer=200
answer=198
answer=3
answer=430
answer=4
answer=12
answer=5
answer=30
answer=6
answer=45
answer=7
answer=154
answer=8
answer=250
answer=120
answer=0
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 SuperMarbles.main(SuperMarbles.java:16)

您已正确获取所有输入,但即使没有更多输入,您仍不断尝试获取它。

in.hasNext()false时,您需要停止。但您根本没有对此进行测试。

此外,如果将最后的调试输出更改为

System.out.println("answer=" + answer + ", id=" + id);

你会发现id永远不等于0,因此你的while循环永远不会结束。

可能还有其他问题,但这是两个很好的开始。祝你好运!

关于Java初学者: Message coming up under General output in java although process was completed,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21971079/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com