我正在尝试创建一个Java程序,它向用户询问圆柱体的直径和高度,它只将输入作为小于2,147,483,648的正整数,然后根据该输入计算体积和表面积。我的问题是尝试验证用户输入,运行错误消息("请输入一个十进制的整数值(小于2,147,483,648):") 如果用户输入单词或无效的数字,然后允许用户输入新的有效答案。
我尝试创建一个私有类来检查用户输入是否有效在程序要求用户输入之后,使用相同的定义整数(直径;高度尚未完成)。 ..)。这也是在进行数学计算以找到体积和表面积之前。 我的问题是当我尝试在volume / SA公式之后关闭公共类时,我的括号被Eclipse编辑器显示为错误。对不起长代码。非常感谢您提前获得任何帮助。
import java.util.Scanner;
public class ContainerCalculator
{
public static void main(String[] args)
{
Scanner scnr = new Scanner(System.in);
int height = 0;
int diameter = 0;
double surfaceArea = 0.0;
double volume = 0.0;
double radius = 0.0;
System.out.println("Welcome to the Container Calculator!");
System.out.println("====================================");
//User prompts to get the diameter and height of the cylinder.
System.out.println("Enter the diameter of a cylinder (in centimeters): ");
diameter = scnr.nextInt();
System.out.println("");
System.out.println("Enter the height of a cylinder (in centimeters): ");
height = scnr.nextInt();
System.out.println("");
}
private static int inputChecker(Scanner scnr) {
int i = 0;
int diameter = -1;
int height = -1;
while (i==0){
while (!scnr.hasNextInt()) {
System.out.println("Please enter an integer value (less than 2,147,483,648) as decimal: ");
scnr.nextLine();
}
while (scnr.hasNextInt()){
diameter = scnr.nextInt();
// check to see if it is negative or past a 32-bit range (within range)
if ((diameter >= 0) && (diameter < 2147483647)) {
i++;
return diameter;
}
else {
System.out.println("Please enter an integer value (less than 2,147,483,648) as decimal digits: ");
scnr.nextLine();
}
}
}
return -1;
}
//VOLUME CALCULATIONS:
radius = diameter / 2.0;
volume = Math.PI * Math.pow(radius, 2.0) * height;
System.out.println("A can with a diameter of " + diameter +
" and a height of " + height + " has ");
System.out.print("\ta volume of ");
System.out.printf("%.2f", volume);
System.out.println(",");
//SURFACE AREA CALCULATIONS:
surfaceArea = (2.0 * Math.PI * radius * height) + (2.0 * Math.PI * Math.pow(radius, 2.0));
System.out.print("\tand a surface area of ");
System.out.printf("%.2f", surfaceArea);
System.out.print(".");
System.out.println("");
System.out.println("=============================================");
System.out.println("Thank you for using the Container Calculator.");
}
答案 0 :(得分:1)
阅读用户输入:
while (true) {
// read line, e.g. String line = reader.readline();
// try to parse line as int, e.g. Integer.valueOf(line); if this does not throw an exception, break;
// catch NumberformatException, print error, next try
}