2016-10-17 9 views
-1

Bellowは次のコードです。ユーザーが許可されたパラメータ外の高さを入力すると現在設定されています。また、整数を入力しない場合、同じエラーメッセージを返す必要があります。INTの代わりにdoubleを入力した場合のIF文の戻りエラー

EQユーザーが70.5を入力すると、同じエラーが発生します。

私は||を試しました。 int == nullしかし、それが適切な方法であるかどうかはわかりません。そのようにも機能しません。

import java.util.*; 

public class HowHealthy 
{ 
    public static void main(String[] args) 
{ 
    String scanName; 
    char scanGender;   
    String strGender;  
    double scanWeight;   
    int scanHeight;   
    int scanAge;    
    int scanLevel;    

    Scanner scan = new Scanner(System.in);   // Creates a new scanner so we can input the users details 

    // Asks for the Person's Name if it is not at least 1 charecter it gives error message and exists program. 
    System.out.print("Person's name: "); 
    scanName = scan.nextLine(); 
    if (scanName.length() < 1) 
    { 
    System.out.println("Invalid name - must be a proper name");        // Error message it displays 
    System.exit(0); 
    } 


    // Asks for the Person's Gender - if its not M or F it returns error and exits program 
    System.out.print(scanName + ", are you male or female (M/F): "); 
    scanGender = scan.nextLine().toUpperCase().charAt(0); 
    if ((scanGender != 'M') && (scanGender != 'F')) 
    { 
    System.out.println("Invalid gender - must be either M or F");        // Error message it displays 
    System.exit(0); 
    } 
    if (scanGender == 'M')   // If M is entered for gender it then assigns male to the strGender variable which is used later 
    { 
    strGender = "male"; 
    }  
    else 
    { 
    strGender = "female";   // If F is entered for gender it then assigns female to the strGender variable which is used later 
    } 


    // Asks for the Person's Weight - if its not at least 100 pounds it will return error and exit program 
    System.out.print(scanName + ", weight (pounds): "); 
    scanWeight = scan.nextDouble(); 
    if (scanWeight < 100.0) 
    { 
    System.out.println("Invalid weight - must be at least 100 pounds");      // Error message it displays 
    System.exit(0); 
    } 

    // Asks for the Person's Height - if its not at least 60 inches and less than 84 inches it will return an error and exits the program. 
    System.out.print(scanName + ", height (inches): "); 
    boolean failed = false; 
    try 
    { 
    scanHeight = scan.nextInt(); 
    } 
    catch(InputMismatchException e) 
    { 
    failed = true; 
    } 
    if (failed || (scanHeight < 60) || (scanHeight > 84)) 
    { 
    System.out.println("Invalid height - must be between 60 to 84 inches, inclusively");  // Error message it displays 
    System.exit(0); 
    } 
// System.out.print(scanName + ", height (inches): "); 
// scanHeight = scan.nextInt(); 
    //if ((scanHeight < 60) || (scanHeight > 84)) 
    //{ 
    /// System.out.println("Invalid height - must be between 60 to 84 inches, inclusively");  // Error message it displays 
    // System.exit(0); 
// } 

    // Asks for the Person's Age - If it is not at least 18 it gives error and exits the program. 
    System.out.print(scanName + ", age (years): "); 
    scanAge = scan.nextInt(); 
    if (scanAge < 18) 
    { 
    System.out.println("Invalid age - must be at least 18 years");        // Error message it displays 
    System.exit(0); 
    } 

    // Prints the following lines so the user can see what activity level they would fall into. 
    System.out.println("\nActivity Level: Use this categories: "); 
    System.out.println("\t1 - Sedentary (little or no exercise, desk job)"); 
    System.out.println("\t2 - Lightly active (little exercise/sports 3-5 days/wk"); 
    System.out.println("\t3 - Moderately active(moderate exercise/sports 3-5 days/wk)"); 
    System.out.println("\t4 - Very active (hard exercise/sports 6 -7 day/wk)"); 
    System.out.println("\t5 - Extra active (hard daily exercise/sports physical job or 2X day \n\t training i.e marathon, contest, etc.)"); 
    System.out.print("\nHow active are you? "); 

    // Asks for the Person's Activity level - must be between 1 to 5 if not gives error and exits the program. 
    scanLevel = scan.nextInt(); 
    if ((scanLevel < 1) || (scanLevel > 5)) 
    { 
    System.out.println("Invalid level - must between 1 to 5");         // Error message it displays 
    System.exit(0); 
    } 

    // Creates a new opbject called scanObject with the Healthy constructor. The inputs are the temporary variables entered above from the scanner. 
    Healthy scanObject = new Healthy(scanName, scanGender, scanWeight, scanHeight, scanAge, scanLevel); 


    System.out.printf("\n%s's information\n", scanObject.getName());         // Prints the Person's name, adds a 's and then information | uses printf 
    System.out.printf("Weight: \t%-4.1f pounds \n", scanObject.getWeight());       // Prints the Person's weight and formats it 
    System.out.printf("Height: \t%-3.1f inches \n", scanObject.getHeight());       // Prints the Person's height and formats it 
    System.out.printf("Age: \t\t%-2d years \n", scanObject.getAge());         // Prints the person's age and formats it 
    System.out.print("These are for a " + strGender + ".\n\n");          // "Prints These are for a" + strGender (which is the temporary variable that was determined from above) 

    System.out.printf("BMR is %.2f \n", scanObject.getBMR());           // Calculates and prints the BMR of the person 
    System.out.printf("BMI is %.2f \n", scanObject.getBMI());           // Calculates and prints the BMI of the person 
    System.out.printf("TDEE is %.2f \n", scanObject.getTDEE());          // Calculates and prints the TDEE of the personjgraspaasd 
    System.out.printf("Your BMI classifies you as %s. \n", scanObject.getWeightStatus());    // Calculates and prints the Weight Status of the person 


    }  
} 
+0

([入力java.util.Scannerを使用しての検証]の可能重複http://stackoverflow.com/questions/3059333/validating-input-using-java-util-スキャナ) – Tom

答えて

0

あなたはそれをキャッチする必要がありますので、そのような場合には、それは、例外がスローされます: "intitializedません" エラーを修正するために

System.out.print(scanName + ", height (inches): "); 
    boolean failed = false; 
    try { 
    scanHeight = scan.nextInt(); 
    } 
    catch(InputMismatchException e) 
    { 
    failed = true; 
    } 
    if (failed || (scanHeight < 60) || (scanHeight > 84)) 
    { 
    System.out.println("Invalid height - must be between 60 to 84 inches, inclusively");  // Error message it displays 
    System.exit(0); 
    } 

UPD を、VARSにデフォルト値を与える:

double scanWeight = 0;   
    int scanHeight = 0;   
    int scanAge = 0;    
    int scanLevel = 0;  
+0

キャッチでこれを行うと、scanHeightが初期化されていなくても上部で初期化されていないため、コンパイルされません。 – Ken

+0

私はこのキャッチを試して、コンパイル時にscanHeightが初期化されていないことを返します。それは先頭に初期化されました。 – Ken

+0

@Kenは初期化を伴う完全なコード例を提供していますので、エラー – maxpovver

0

scanHeight = scan.nextInt();

これは、入力としてのみINTがかかります。入力に10進数が指定されていると、エラーを返します。そのエラーを処理したい場合は、try catchステートメントを使用してscanHeight = scan.nextInt();ステートメントをラップすることをお勧めします。

+0

さて、それを見て病気を見てください。私はそれが私とエラーを与えることを知っているが、if文から同じ単純なエラーを与える必要があります。 – Ken

0

を見てから、 Java Scanner.nextInt()のドキュメントは、入力がintでなければ例外をスローします。

例外をキャッチし、実行している範囲テストと同じエラーを返すだけで済みます。

0

は、次のことを試してください。

try{ 
    scanHeight = scan.nextInt(); 
}catch(Exception e){//if the user enters a floating point number this would catch the exception and notifies user to enter whole numbers only 
    System.out.println("You should enter whole numbers only");  // Error message it displays 
    System.exit(0); 
}if ((scanHeight < 60) || (scanHeight > 84)){ 
     System.out.println("Invalid height - must be between 60 to 84 inches, inclusively");  // Error message it displays 
     System.exit(0); 
} 
関連する問題