Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 7 of 7

Thread: Try-Catch For Specific Numbers?

  1. #1
    Junior Member
    Join Date
    Dec 2017
    Posts
    18
    Thanks
    13
    Thanked 1 Time in 1 Post

    Default Try-Catch For Specific Numbers?

    Hey guys, right now I need the user to either input a 1 or a 2

    I am using the following Try-Catch
    while (true)
                try {
                    num1 = Integer.parseInt(kb.nextLine());
                    break;
                } catch (NumberFormatException nfe) {
    System.out.print("That is not a number: ");
    }

    This will limit the possibility to a number, however users can still input any number such as 3, 4, 5, etc.

    I have If statements for 1 and 2 and an else for 3

    However, how can I re-request an input if any other value is entered. Im slightly confused


    Here is the entire code for reference:

    package salesperson_part1;
     
    //Imports
    import java.io.IOException; 
    import java.io.InputStreamReader;  
    import java.io.BufferedReader; 
    import java.util.Scanner;
     
     
    public class DriverCalculator {
     
     
        public static void main(String args[]){
     
            //Initializations
            double annualSales;
            SalesPerson sales;
     
               Scanner kb = new Scanner(System.in);
     
            int num1;
            System.out.print("Enter 1 for Total Commission and Annual Sales Calculator,\n"
                        + "Enter 2 for Sales Person Compensation Comparison Calculator: ");
            while (true)
                try {
                    num1 = Integer.parseInt(kb.nextLine());
                    break;
                } catch (NumberFormatException nfe) {
                    System.out.print("That is not a number: ");
                }
     
        if (num1 == 1) {
     
                     //Request Total Sales
            Scanner input=new Scanner(System.in);
            System.out.print("\nThis program will calculate Total Compensation based"
                    + " upon\nthe percentage met of the $120,000 Annual Sales Target."
                    + "\nThis program will also output a table of possible Total"
                    + " Compensations\nin increments of $5,000 up to 1.5 times your inputted Annual Sales\n\n"
                    + "Please enter your Total Annual Sales: ");
     
     
             //Check for Correct Entry Data
             try { 
                BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); 
                String line = in.readLine().trim(); 
     
                //Check for Null Entry
                   if (line == null || line.length() == 0) { 
                      System.out.println("You did not enter a value"); 
                      return; 
                } 
     
                   //Declare Annual Sales and Replace Commas/Dollar Signs
                    annualSales = Double.parseDouble(line.replaceAll(",", "").replaceAll("\\$", ""));
     
                //Check for numerical value
            }   catch (NumberFormatException exception) { 
                     System.out.println("Error: Not a valid sales amount."); 
                     return; 
     
                //Check for IOException
            }   catch (IOException exception) { 
                     System.out.println("Error: " + exception.getLocalizedMessage()); 
                     return; 
            } 
     
             //Declare Sales
            sales=new SalesPerson(annualSales);
     
            //Output Total Commission
            System.out.println("\nYour Total Commission for the year is: $" +
                    SalesPerson.commission);
     
            //Output Total Compensation
            System.out.println("Your Total Compensation for the year is: $"+
                    String.format("%.2f", sales.getTotalAnnualCompensation())+ "+\n");
     
     
            //Output Table Headers
            System.out.println("Total Sales     |      Total Compensation");
     
            //Set UpperLimit at 150%
            int upperlimit = (int) ((annualSales/2)/5000);
     
            //Calculate Total Compensation in relevance with Total Sales
             for(int i=0;i<=upperlimit;i++){
              sales=new SalesPerson(annualSales);
              System.out.println(" $"+ annualSales+"       |         "
                      +"$"+String.format("%.2f", sales.getTotalAnnualCompensation()));
              annualSales+=5000;   
             }  
        }
         if (num1 == 2) {
                 System.out.print("\nSales Person Comparison Program\n");
             }
     
     
        else {
        System.out.print("\nYou did not enter 1 or 2\n");
    }
    }
    }

  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    22,400
    Thanks
    53
    Thanked 2,399 Times in 2,352 Posts

    Default Re: Try-Catch For Specific Numbers?

    how can I re-request an input if any other value is entered.
    One way would be to use a while loop that keeps looping until a valid value is entered.
    If you don't understand my answer, don't ignore it, ask a question.

  3. The Following User Says Thank You to Norm For This Useful Post:

    Deployment (December 19th, 2017)

  4. #3
    Junior Member
    Join Date
    Dec 2017
    Posts
    18
    Thanks
    13
    Thanked 1 Time in 1 Post

    Default Re: Try-Catch For Specific Numbers?

    Quote Originally Posted by Norm View Post
    One way would be to use a while loop that keeps looping until a valid value is entered.
    I tried that and it worked for checking for 1 and 2, but then after the while loop was initiated if a string was entered the program would fail again. Is there a way to incorporate the try-catch into the whole loop to check for 1 and 2 as well as check for strong values

    If so please help me write this

    Thank you,

    - Deployment

  5. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    22,400
    Thanks
    53
    Thanked 2,399 Times in 2,352 Posts

    Default Re: Try-Catch For Specific Numbers?

    try/catch blocks are for handling exceptions. Not what is needed here.
    You need to have tests in the code that check for valid values and react to them. For example a while loop would test for valid values and exit when the value is good and loop back when it was not.

    Can you post the while loop code that you tried?
    If you don't understand my answer, don't ignore it, ask a question.

  6. The Following User Says Thank You to Norm For This Useful Post:

    Deployment (December 19th, 2017)

  7. #5
    Junior Member
    Join Date
    Dec 2017
    Posts
    18
    Thanks
    13
    Thanked 1 Time in 1 Post

    Default Re: Try-Catch For Specific Numbers?

    Quote Originally Posted by Norm View Post
    try/catch blocks are for handling exceptions. Not what is needed here.
    You need to have tests in the code that check for valid values and react to them. For example a while loop would test for valid values and exit when the value is good and loop back when it was not.

    Can you post the while loop code that you tried?
    Yes

     num1 = Integer.parseInt(num.nextLine());
     
                    while (num1 != 1 && num1 != 2 ) {
                        System.out.print("You did not enter 1 or 2: ");
                         num1 = Integer.parseInt(num.nextLine());
                }

    So if the value inputted is not 1 or 2 and a number it will loop again. How can I also make it loop again if a string is inputted?

    Thank you,
    - Deployment
    Last edited by Deployment; December 18th, 2017 at 09:58 PM.

  8. #6
    Member John Joe's Avatar
    Join Date
    Jun 2017
    Posts
    261
    My Mood
    Amused
    Thanks
    8
    Thanked 18 Times in 18 Posts

    Default Re: Try-Catch For Specific Numbers?

    How can I also make it loop again if a string is inputted?
    You can use do-while loop and add boolean inside catch block
     public static void main(String[] args) {
            Scanner num = new Scanner(System.in);
            boolean ans = true;
            do {
                try {
                    int num1 = Integer.parseInt(num.nextLine());
                    while (num1 != 1 && num1 != 2) {
                        System.out.print("You did not enter 1 or 2: ");
                        num1 = Integer.parseInt(num.nextLine());
                    }
                    break;
                } catch (NumberFormatException ex) {
                    System.out.println("Only number is allowed");
                    ans = false;
                }
            } while (ans == false);
        }
    Last edited by John Joe; December 18th, 2017 at 10:23 PM.
    Whatever you are, be a good one

  9. The Following User Says Thank You to John Joe For This Useful Post:

    Deployment (December 19th, 2017)

  10. #7
    Junior Member
    Join Date
    Dec 2017
    Posts
    18
    Thanks
    13
    Thanked 1 Time in 1 Post

    Default Re: Try-Catch For Specific Numbers?

    Quote Originally Posted by John Joe View Post
    You can use do-while loop and add boolean inside catch block
     public static void main(String[] args) {
            Scanner num = new Scanner(System.in);
            boolean ans = true;
            do {
                try {
                    int num1 = Integer.parseInt(num.nextLine());
                    while (num1 != 1 && num1 != 2) {
                        System.out.print("You did not enter 1 or 2: ");
                        num1 = Integer.parseInt(num.nextLine());
                    }
                    break;
                } catch (NumberFormatException ex) {
                    System.out.println("Only number is allowed");
                    ans = false;
                }
            } while (ans == false);
        }
    Thank you, this worked perfectly after moving the "int num1 = Integer.parseInt(num.nextLine());" outside of the loop and fixing a few brackets. Also changed "boolean ans = true;" to "boolean ans;"

    This forum is great, and I appreciate the help more than you can imagine

    - Deployment

Similar Threads

  1. Help With Setting Specific Numbers in Specific JTextFields
    By Ezra Zike in forum What's Wrong With My Code?
    Replies: 0
    Last Post: April 26th, 2014, 01:10 AM
  2. catch negative numbers
    By garry in forum Exceptions
    Replies: 6
    Last Post: November 8th, 2013, 09:05 PM
  3. Generating random numbers in java without repeating a specific number
    By ojonugwa in forum What's Wrong With My Code?
    Replies: 9
    Last Post: August 26th, 2013, 12:42 AM
  4. Replies: 4
    Last Post: February 10th, 2013, 10:58 PM
  5. Referring to specific numbers in an integer?
    By Scorks in forum What's Wrong With My Code?
    Replies: 8
    Last Post: February 7th, 2013, 04:00 PM