[英]do while loop, InputMismatchException
我是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+ ".");
}
}
在Java中,这称为自动类型提升。 这是类型提升的基本规则
类型提升规则
扩展转换不会丢失有关值大小的信息。 例如,将int值分配给double变量。 这种转换是合法的,因为双精度数比整数宽。 Java的扩展转换是
从字节到短整数,整数,长整数,浮点数或双精度数
从short到int,long,float或double
从char到int,long,float或double
从int到long,float或double
从多头到浮动或双倍
从花车到双人
double是最广泛的基本类型,正是由于这些规则,当您在程序中输入整数时,它们被提升为double
尝试这个:
公共静态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 + ".");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.