gpt4 book ai didi

java - Java 中的 hasNextDouble 方法出现问题

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

在我的程序中,我让用户输入半径值,然后程序输出面积和周长。

我想确保用户输入数字,因此我使用了 hasNextDouble() 方法。但它并不能完全正常工作。

当程序运行我在下面的代码中加粗的第一个 while 循环时(显然,我不能加粗代码,所以它是带有星号的代码),在下面的代码中,单词“请输入数字>”按预期显示.

但是,如果程序运行我加粗的第二个 while 循环(嵌套在测试用户输入的数字是否为正的 while 循环内),“请输入数字 > ”会出现两次。

我不明白为什么这些词会打印两次。有人可以帮忙吗?

/**
* Uses the Circle class to calculate area and perimeter of a circle based on a user-provided radius.
*
* @author Brittany Gefroh
* @version 1.0
*/

//Import the Scanner class
import java.util.Scanner;

public class CircleTest
{
public static void main (String [] args)
{
//Initialize a Scanner object
Scanner scan = new Scanner(System.in);

//Create new Circle object
Circle circle1 = new Circle();

//Declare variables
double input;
String garbage;
String answer;

//Do/while loop answer is Y or y
do
{
//Ask user for a radius value
System.out.print("Enter a radius value > ");

**while ( ! scan.hasNextDouble())
{
garbage = scan.nextLine();
System.out.print("\nPlease enter a number > ");
}**

//Assign user input to the input variable
input = scan.nextDouble();

//Test if input is a positive number
while (input <= 0)
{
//Prompt user for a new radius value
System.out.println("Radius must be greater than 0");
System.out.print("\nEnter a radius value > ");

**while ( ! scan.hasNextDouble())
{
garbage = scan.nextLine();
System.out.print("\nPlease enter a number > ");
}**

//Assign user input to the input variable
input = scan.nextDouble();
}

//Run the setRadius method to change the radius
circle1.setRadius(input);

//Print blank space
System.out.println("");

//Display output
System.out.println("The radius is " + circle1.getRadius());
System.out.println("The area is " + circle1.getArea());
System.out.println("The perimeter is " + circle1.getPerimeter());

//Print blank space
System.out.println("");

//Ask user if he/she wants to try again
System.out.print("Would you like to try again? Y or N > ");
answer = scan.next();

//Print blank space
System.out.println("");

}while (answer.equalsIgnoreCase("Y"));

}
}

最佳答案

更改:

answer = scan.next();

致:

scan.nextLine();
answer = scan.nextLine();

也许您应该尝试通过创建一种专门的方法来简化此代码,用于读取带有验证的 double ?还要尝试思考为什么有这些“空”nextLine() 操作。这些有必要吗?

编辑...

问题是 scan.nextDouble(); 没有删除 EOL 标记(行尾)。 scan.next(); 也是如此。那是你的问题。 EOL 标记通过 while 条件进行分析,显示:

"Please enter a number > " <immediate EOL answer which was left in scanner>
"Please enter a number > " <now we are waiting for user input>

关于java - Java 中的 hasNextDouble 方法出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15648242/

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