问题描述
限时送ChatGPT账号..编写一个代码,从标准输入中逐行读取学生成绩列表,直到没有更多行可供读取或遇到空行.
Write a code that reads a list of student grades from standard input line-by-line until there are no more lines to read or an empty line is encountered.
但是,无论如何我都无法退出循环.我试着写Scanner input = new Scanner(input.hasNext());
否则中断但它不起作用
However, I cannot exit the loop anyway. I tried to write
Scanner input = new Scanner(input.hasNext());
and else break but it is not working
public class NumInput {
public static void main(String [] args) {
float min = Float.MAX_VALUE;
float max = Float.MIN_VALUE;
float total=0;
int count=0;
Scanner input = new Scanner(System.in);
while (input.hasNext()) {
float val = input.nextFloat();
if (val < min) {
min = val;
}
if (val > max) {
max = val;
}
count++;
total += val ;
}
float average = (float) total / count;
System.out.println("min: " + min);
System.out.println("max: " + max);
System.out.println("The Average value is: " + average);
}
}
推荐答案
代替while(input.hasNext());
,尝试while(input.hasNextFloat());
如果它总是一个 float
类型.
Instead of while(input.hasNext());
, try while(input.hasNextFloat());
if it's always going to be a float
type.
此外,while(input.hasNextFloat());
将继续读取用户的输入,直到一个非 float
值(或非 int
值)输入.所以你可以输入1
和2
最后q
,然后因为q
不是float
/int
它将退出循环.
Also, while(input.hasNextFloat());
will continue reading the user's input until a non float
value (or non int
value) is entered. So you can enter 1
and 2
and finally q
, then because q
is not an float
/int
it'll exit the loop.
解决此问题的更具体方法是执行以下操作:
A more specific way of solving this would be to do the following:
while(input.hasNextLine()) {
String command = input.nextLine();
if(command.equals("")) {
System.out.println("breaking out of the loop");
break;
}
// rest of the code but make sure to use Float.parseFloat() on the `command`;
}
这个文档有很好的例子以及对 hasNextFloat()
、hasNextLine()
和 parseFloat()
的解释:http://docs.oracle/javase/7/docs/api/java/util/Scanner.html
This documentation has good examples as well as explanation for hasNextFloat()
, hasNextLine()
, and parseFloat()
: http://docs.oracle/javase/7/docs/api/java/util/Scanner.html
这篇关于在Java中看到空行时如何中断while循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论