1

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

我想确保用户输入一个数字,所以我使用了 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"));

}
}
4

1 回答 1

2

改变:

answer = scan.next();

至:

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

也许您应该尝试通过创建一个专门的方法来简化此代码,以读取带有验证的双精度?也试着想想为什么你有这些“空”的 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>
于 2013-03-26T22:23:57.097 回答