gpt4 book ai didi

java - 在使用 in.nextDouble() 时遇到问题

转载 作者:塔克拉玛干 更新时间:2023-11-01 23:10:09 25 4
gpt4 key购买 nike

我正在尝试在下面的程序中使用 in.nextDouble() 方法来计算一些数字的平均值。

import java.util.Scanner;

public class Average
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
double value;
int count = 0;
double sum = 0;
System.out.print("Enter a value, Q to quit: ");
while (in.hasNextDouble())
{
value = in.nextDouble();
sum = sum + value;
count++;
System.out.print("Enter a value, Q to quit: ");
}
double average = sum / count;
System.out.printf("Average: %.2f\n", average);
}
}

此代码有效,但我不明白为什么。当我第一次使用 while(in.hasNextDouble()) 时,我还没有初始化任何东西,为什么循环会起作用?

最佳答案

当您在没有输入的情况下调用 in.hasNextXXX() 时,Scanner 等待输入。

因此,它在第一种情况下等待您输入一个值。

一旦您输入非双数的内容(并按回车键),它将立即退出。

Scanner#hasNext() 的文档

Returns true if this scanner has another token in its input. This method may block while waiting for input to scan. The scanner does not advance past any input.

对于所有 hasNextXXX() 操作都是如此。

关于java - 在使用 in.nextDouble() 时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32007255/

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