簡體   English   中英

如果用戶輸入 double 而不是 INT,則使用 IF 語句返回錯誤

[英]Return error with IF statement if user enters double instead of INT

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


  }     
}

scanHeight = scan.nextInt();

這只會將 int 作為輸入。 如果輸入中給出了十進制數,它將返回錯誤。 如果你想處理那個錯誤,那么我建議使用 try catch 語句來結束你的scanHeight = scan.nextInt(); 陳述。

在這種情況下,它會拋出異常,因此您必須捕獲它:

 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;     

從查看Java Scanner.nextInt()的文檔來看,如果輸入不是 int,它將拋出異常。

您只需要捕獲異常並返回與您正在執行的范圍測試相同的錯誤。

嘗試以下操作:

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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM