-1

Bellow is my following code, it is currently set if the user enters a height outside of the allowed parameters. I also need it to return the same error message if they do not enter a whole number.

EQ user enters 70.5 it gives same error.

I have tried the || int == null but don't know if that's a proper way to do it. It also does not work that way.

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


  }     
}
Ken
  • 29
  • 1
  • 6
  • Possible duplicate of [Validating input using java.util.Scanner](http://stackoverflow.com/questions/3059333/validating-input-using-java-util-scanner) – Tom Oct 17 '16 at 15:13

4 Answers4

0

scanHeight = scan.nextInt();

This will only take int as an input. It will return an error if a decimal number is given in input. If you want to handle that error then I recommend using try catch statement to wrap up your scanHeight = scan.nextInt(); statement.

Akshansh Jain
  • 277
  • 1
  • 3
  • 16
  • Okay, ill look into doing that to see. I know it gives me and error as is but need it to give same simple error from if statement. – Ken Oct 17 '16 at 15:09
0

In such case it throws exception, so you have to catch it:

 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 to fix "not intitialized" error, give vars default values:

  double scanWeight = 0;        
  int scanHeight = 0;          
  int scanAge = 0;               
  int scanLevel = 0;     
maxpovver
  • 1,417
  • 11
  • 23
  • Doing it with the catch it now won't compile because it says the scanHeight was not initialized even though it was initialized at the top. – Ken Oct 17 '16 at 15:15
  • I tried this catch and now returns that scanHeight is not initialized when compiling. It was initialized at the top. – Ken Oct 17 '16 at 15:16
  • @Ken give full code example with intitialization so we can see error – maxpovver Oct 17 '16 at 15:19
  • i edited top, sorry took a little bit to make it show up as precode – Ken Oct 17 '16 at 15:30
  • Its a rule in java that if a variable is defined inside a function you have to explicitly initialize when you create it... so just say `int scanHeight = 0;` – Shreyas Sarvothama Oct 17 '16 at 15:33
  • int scanHeight = 0; max power is what i edited at the top, now i know for future use. Thanks for all your help – Ken Oct 17 '16 at 15:35
0

From looking at the documentation for Java Scanner.nextInt() it will throw an exception if the input is not an int.

You just need to catch the exception and return the same error as for the range test you're doing.

bluemonki
  • 91
  • 3
0

try the following:

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