如果用户输入double而不是INT,则返回IF语句错误

时间:2016-10-17 15:02:46

标签: java

Bellow是我的以下代码,如果用户输入允许参数之外的高度,则会设置它。如果他们不输入整数,我还需要它返回相同的错误消息。

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


  }     
}

4 个答案:

答案 0 :(得分:0)

scanHeight = scan.nextInt();

这只会将int作为输入。如果在输入中给出十进制数,它将返回错误。如果您想处理该错误,那么我建议使用try catch语句来包装您的scanHeight = scan.nextInt();语句。

答案 1 :(得分:0)

在这种情况下它抛出异常,所以你必须抓住它:

 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     修复“not intitialized”错误,给出vars默认值:

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

答案 2 :(得分:0)

通过查看Java Scanner.nextInt()的文档,如果输入不是int,它将抛出异常。

您只需捕获异常并返回与您正在进行的范围测试相同的错误。

答案 3 :(得分: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);
}