gpt4 book ai didi

java - 使用 sc.hasNextLine() 进行无限循环

转载 作者:行者123 更新时间:2023-12-01 18:04:20 25 4
gpt4 key购买 nike

我正在尝试使用输入,但是我遇到了麻烦...如果我使用下面的代码,它还没有结束...所以我处于无限循环中。即使我的输入已到达文件结尾,它也会写类似的内容:

...
A number has not been parsed from line n
A number has not been parsed from line n+1
A number has not been parsed from line n+2
... (infinite)

但我想代替这个:

...
End of input detected!

输入看起来像这样:

1
2
3
4
5
double[] numbers = new double[10];
int counter_number = 0;
while (sc.hasNextLine()) {
...
line++;
if(sc.hasNextDouble()) {
numbers[counter_number] = sc.nextDouble();
counter_number++;
}
else{
System.out.println("A number has not been parsed from line "+ line);
continue;
}
if (sc.hasNextLine() == false) {
System.err.println("End of input detected!");
}
if (((counter_number)==10) || ((sc.hasNextLine() == false)
...
counter_number = 0;
}
}

虽然这个循环永远不会结束?我看到他们使用“while (sc.hasNextLine())”的教程,它就完成了。我是java初学者。

最佳答案

static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
double[] numbers = new double[10];
int counter_number = 0;
int line = 0;

while (sc.hasNextLine()){

line++;

String thisLine = sc.nextLine();
// this is what i wrote.

if(thisLine.trim().isEmpty()) {
// if the line is empty, will exit the loop.

System.out.println("lines: "+line); // lines
System.out.println("End of input detected!"); // end.
break;
}

try {
// if the input is a double
numbers[counter_number] = Double.parseDouble(thisLine);
counter_number++;

} catch (NumberFormatException e) {
// if not
System.out.println("A number has not been parsed from line "+ line);
continue;
}

// idk
if (counter_number == numbers.length) {
counter_number = 0;
}
};

}

修复。我不会关闭扫描仪...你试试这个。当我输入空行时,此代码结束。

关于java - 使用 sc.hasNextLine() 进行无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60581658/

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