我对java很陌生,我正在开发一个计算用户BMI的程序。我不明白为什么我的do while循环不适用于我的InputMismatchException。第一次它会说它是不正确的,但是如果你第二次输入它,它就会崩溃。任何帮助都将不胜感激。
import java.util.*;
public class W8
{
public static void main (String[] args)
{
//Utilities
Scanner in = new Scanner(System.in);
//Variables
double height = 0.0;
double weight = 0.0;
boolean error = false;
double bmi = 0.0;
do
{
try
{
error = false;
while (height <=0)
{
System.out.println("Enter height in inches:");
height = in.nextDouble();
}
}
catch (InputMismatchException e)
{
in.nextLine();
System.out.println("Invalid inches value. Must be a decimal number.");
System.out.println("Re-enter height in inches:");
height = in.nextDouble();
error = true;
}
}while (error);
do
{
try
{
error = false;
while (weight <=0)
{
System.out.println("Enter weight in pounds:");
weight = in.nextDouble();
}
}
catch (InputMismatchException e)
{
in.nextLine();
System.out.println("Invalid pounds value. Must be a decimal number.");
System.out.println("Re-enter weight in pounds:");
weight = in.nextDouble();
error = true;
}
}while (error);
//bmi calculation
bmi = (weight/(height*height))*703;
//Outputs
System.out.println("Height = " +height+".");
System.out.println("Weight = " +weight+".");
System.out.println("Body mass index = " +bmi+ ".");
}
}发布于 2015-03-24 03:09:16
试试这个:
公共静态空洞主(String[] args) {
// Utilities
Scanner in = new Scanner(System.in);
// Variables
double height = 0.0;
double weight = 0.0;
boolean error = false;
double bmi = 0.0;
System.out.println("Enter height in inches:");
while (height <= 0) {
try {
height = in.nextDouble();
} catch (InputMismatchException e) {
height = -1;
System.out
.println("Invalid inches value. Must be a decimal number.");
System.out.println("Re-enter height in inches:");
in.nextLine();
error = true;
}
}
System.out.println("Enter weight in inches:");
while (weight <= 0) {
try {
weight = in.nextDouble();
} catch (InputMismatchException e) {
weight = -1;
System.out
.println("Invalid inches value. Must be a decimal number.");
System.out.println("Re-enter weight in inches:");
in.nextLine();
error = true;
}
}
// bmi calculation
bmi = (weight / (height * height)) * 703;
// Outputs
System.out.println("Height = " + height + ".");
System.out.println("Weight = " + weight + ".");
System.out.println("Body mass index = " + bmi + ".");
}发布于 2015-03-24 02:49:42
这在Java中被称为自动类型提升。下面是类型提升的基本规则
类型提升规则
扩大转换不会丢失有关值大小的信息。例如,将int值赋值给一个双变量。这种转换是合法的,因为双倍比ints宽。Java的不断扩大的转换是
从字节到短、int、长、浮点数或双字节 从短到整,长,浮动或双 从一个字符到一个int,一个长的,一个浮点数,或一个双 从一个int到一个长,一个浮动,或一个双 从长到浮动或双倍 从浮动到双倍
double是最宽的基元类型,因为有了这些规则,当您在程序中输入整数时,它们就被提升为double。
https://stackoverflow.com/questions/29223934
复制相似问题