我是java新手,我正在开发一个计算用户BMI的程序。我无法弄清楚为什么我的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+ ".");
}
}
答案 0 :(得分:0)
这在Java中称为自动类型提升。以下是类型促销的基本规则
类型促销规则
扩展转换不会丢失有关值的大小的信息。例如,将int值分配给double变量。这种转换是合法的,因为双倍比整数更宽。 Java的扩展转换是
从一个字节到一个短,一个int,一个long,一个float或一个double
从short到int,long,float或double
从char到int,long,float或double
从int到long,float或double
从长到浮动或双重
从浮动到双重
double是最宽的原始类型,正是由于这些统治,当你在程序中输入整数时,它们被提升为double
答案 1 :(得分:0)
试试这个:
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;
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 + ".");
}