2016-11-01 70 views
0

现在这个问题可能在此之前被问过,但是我找不到它。所以我很抱歉。Java程序在没有提示的情况下循环两次

出于某种原因,我的代码似乎运行两次,即使通过代码我只要求输入一次。有人能指导我解决我的错误吗?

谢谢。

import java.util.Scanner; 

public class BMI 
{ 

    static Scanner kybd = new Scanner(System.in); 

public static void main(String[] args) 
{ 
    System.out.println("Height in inches: " + heightInInches()); 
    System.out.println("Weight in pounds: " + weightInPounds()); 
    System.out.println(outputBMI(heightInInches(),weightInPounds())); 
} 

public static int heightInInches() 
{ 

    System.out.print("Enter your height in feet: "); 
    int feet = kybd.nextInt(); 

    //feet validation 
    while(feet < 2 || feet > 7) 
    { 
     System.out.println("Input not vaild."); 

     System.out.print("Enter your height in feet: "); 
     feet = kybd.nextInt(); 
    } 

    System.out.print("Enter your height in inches: "); 
    int inches = kybd.nextInt(); 

    //inches validation 
    while(inches < 0 || inches > 13){ 
     System.out.println("Input not vaild."); 
     System.out.print("Enter your height in inches: "); 
     inches = kybd.nextInt(); 
    } 

    int totalInches = inches + (feet * 12); 

    return totalInches; 

} 

public static int weightInPounds() 
{ 
    System.out.print("Enter your weight in stone: "); 
    int stone = kybd.nextInt(); 

    //stone validation 
    while(stone < 3 || stone > 30) 
    { 
     System.out.println("Input invalid."); 
     System.out.print("Enter your height in stone: "); 
     stone = kybd.nextInt(); 
    } 

    System.out.print("Please enter your weight in pounds: "); 
    int pounds = kybd.nextInt(); 

    //pounds validation 
    while(pounds < 0 || pounds > 30) 
    { 
     System.out.println("Input invalid."); 
     System.out.print("Please enter your weight in pounds: "); 
     pounds = kybd.nextInt(); 
    } 

    int totalPounds = pounds + (stone * 14); 

    return totalPounds; 
} 

public static double outputBMI(double height, double weight) 
{ 
    double BMI = (weight * 703)/(height/height); 

    return BMI; 
} 

}

+3

在你的第三个'println'主要方法。你再次调用'heightInInches()'和'wightInPounds()'。您应该在第一次调用中保存返回值并将它们发送到'outputBMI()'方法 – rafid059

+0

您不仅要求输入一次。您多次调用'heightInInches()',每次调用它时,都会要求输入。 – nhouser9

+0

@RafiduzzamanSonnet我很困惑,你的意思是?如果它帮助我的目标是以英寸为单位调用高度并显示它。以磅为单位称重并显示。然后计算BMI并显示。 – Josh

回答

0

正如许多在您需要将您heightInInchesweightInPounds只有一次调用和存储在某些局部变量的值在main方法的意见mentionned然后在需要的地方,你重用这些变量。你可以例如更新你的主要方法是这样的:

public static void main(String[] args) 
{ 
    int height = heightInInches(); 
    int weight = weightInPounds(); 
    System.out.println("Height in inches: " + height); 
    System.out.println("Weight in pounds: " + weight); 
    System.out.println(outputBMI(height,weight)); 
} 
相关问题