在我的程序中,我让用户输入一个半径值,然后程序输出区域和周长。
我想确保用户输入一个数字,所以我使用了hasNextDouble()方法。但是,它并没有完全正常工作。
当程序运行第一个while循环时,我在下面的代码中粗体显示(显然,我不能加粗代码,所以它是带有星号的代码),单词“Please enter a number>”显示为意图。
但是,如果程序运行我加粗的第二个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"));
}
}
答案 0 :(得分:2)
变化:
answer = scan.next();
要:
scan.nextLine();
answer = scan.nextLine();
也许您应该尝试通过创建一个专门的方法来读取double并附加验证来简化此代码?还要试着想一想为什么你有这些'空'的nextLine()操作。这些是必要的吗?
编辑...
问题是scan.nextDouble();
不会删除EOL标记(End Of Line)。与scan.next();
相同。那是你的问题。 EOL标记在 条件下进行分析,并显示:
"Please enter a number > " <immediate EOL answer which was left in scanner>
"Please enter a number > " <now we are waiting for user input>