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 5 of 5

Thread: Need help with simple calc java program

  1. #1
    Junior Member
    Join Date
    Nov 2012
    Posts
    5
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Need help with simple calc java program

    Trying to figure out what I'm doing wrong in my programming assignment. I know I could more than likely clean it up and make it much more efficient, but I'm just crazy bad at programming. So, i'll post m assignment and my code and let some more experienced coders look at it.

    1. Prompt the user for two integers.
    2. Display a menu with the following options:
    1. Add numbers
    2. Subtract numbers
    3. Quit

    3. Prompt the user for a single integer that is either 1,2, or 3.
    4. If the user enters an invalid selection, redisplay the menu and prompt them again. Continue this until you get a valid response (1,2,or 3). You must use a loop to do this.
    5.If the user selects ‘3’ then exit the program.
    6.Perform the associated operation (add or subtract) on the previously entered two integers and display the result. Return to step ‘1’ and continue in this manner until the user selects ‘3’ to exit the program.
    7.Name the class CalcJava and save program as CalcJava.java
    8.Submit the program using the WA3 link above.
    So far I have the following code which works fine, seemingly, until I enter some non integer value for the inputs to get added/subtracted or menu choice. In which case errors get thrown out.

    import java.util.Scanner;
     
    public class CalcJava 
    {
     
    	public static void main(String[] args) 
    	{
     
    		int value1 = 0;
    		int value2 = 0;
    		int menuChoice = 0;
    		Scanner input = new Scanner(System.in);
     
     
     
    		while(menuChoice != 3)
    		{
     
     
    			System.out.printf("Please enter first number : ");
    			value1 = input.nextInt();
    			System.out.printf("Please enter second number : ");
    			value2 = input.nextInt();
     
     
    			calcMenu();
     
    			menuChoice = input.nextInt();
     
    			if(menuChoice % 1 != menuChoice)
    				calcMenu();
     
     
    			switch(menuChoice)
    			{
    			case 1:
    				 calcAdd(value1, value2);
    				break;
    			case 2:
    				 calcSubtract(value1, value2);
    				break;
    			case 3:
    				System.out.println("\tGoodbye!");
    				break;
    			default :
    				System.out.println("\tInvalid input :: Please enter a value of 1, 2, or 3");
     
    			}
    		};
     
     
    		input.close();
     
    	}
     
    	public static void calcMenu()
    	{
    		System.out.println("\t\t\tWelcome to Java Calculator v1\n\n");
    		System.out.println("\t1. to add two numbers.\n");
    		System.out.println("\t2. to substract two numbers.\n");
    		System.out.println("\t3. to exit.\n");
    		System.out.printf("Please enter a selection: >");
    	}
     
    	public static int calcAdd(int value1, int value2)
    	{
    		int input1 = value1;
    		int input2 = value2;
    		int resultAdd = 0;
    		resultAdd = input1 + input2;
    		System.out.println("The sum of " + input1 + " and " + input2 + " is > " + resultAdd);
    		return resultAdd;
    	}
     
    	public static int calcSubtract(int value1, int value2)
    	{
    		int input1 = value1;
    		int input2 = value2;
    		int resultSub = 0;
    		resultSub = input1 - input2;
    		System.out.println("The difference of " + input1 + " and " + input2 + " is > " + resultSub);
    		return resultSub;
    	}
     
     
    }
    The error code generated is:
    Exception in thread "main" java.util.InputMismatchException
    at java.util.Scanner.throwFor(Unknown Source)
    at java.util.Scanner.next(Unknown Source)
    at java.util.Scanner.nextInt(Unknown Source)
    at java.util.Scanner.nextInt(Unknown Source)
    at CalcJava.main(CalcJava.java:21)
    Now, I'm guess using the Switch case statement is probably a bad idea for this. Also, I don't think getting input values from user before menu selection is a good idea either. I'm thinking while loop is sufficient, but probably should use if statements inside, or some type of nested loops? I'm really having a hard time with this, and the book we use (Java Programming: Joyce Farrell: 9781111529444: Amazon.com: Books)

    Any help or guidance is appreciated.


  2. #2
    Member
    Join Date
    Jun 2012
    Location
    Left Coast, USA
    Posts
    451
    My Mood
    Mellow
    Thanks
    1
    Thanked 97 Times in 88 Posts

    Default Re: Need help with simple calc java program

    Quote Originally Posted by jace5869 View Post
    Trying to figure out what I'm doing wrong...
    ...
    The error code generated is:
    Exception in thread "main" java.util.InputMismatchException...
    I don't think you have necessarily done anything "wrong" in the program. It's just that nextInt() throws an "Input Mismatch" exception if you feed it something that it doesn't perceive to be an integer. An uncaught exception will terminate the program after printing some kind of message.

    Java provides a mechanism for catching, handling, and recovering from certain types of exceptions. If the subject hasn't appeared in your text yet, maybe you will cover it later. (Or, maybe it was alluded to, but didn't make sense if they didn't show how exceptions could be caught.)

    Anyhow, here's a simple example of catching the kind of exception that you saw:

    import java.util.*;
     
    public class Z {
     
        public static void main(String [] args) {
     
            Scanner keyboard = new Scanner(System.in);
            int n = 0;
            while (n >= 0) {
                System.out.printf("Enter a non-negative integer: ");
     
                try {
                    n = keyboard.nextInt();
                    keyboard.nextLine(); // Eat the rest of the line
                }
                catch(InputMismatchException e) {
                    System.out.println("Invalid input. Not an integer.\n");
                    keyboard.nextLine(); // Eat the rest of the line
                    n = 0; // Make absolutely sure that the loop will be repeated
                    continue; // Go back to top of loop
                } // End try-catch block
     
                System.out.println("You entered " + n);
                System.out.println();
            } // End while loop
     
            if (n == -42) {
                System.out.println("Don't panic!");
            }
     
            System.out.println("\nGoodbye for now.");
     
        } // End main
     
    } // End class definition


    A run: Computer output is blue, user input is black:


    Enter a non-negative integer: 42
    You entered 42

    Enter a non-negative integer: 33 And some more stuff
    You entered 33

    Enter a non-negative integer: 123This can't be good, can it?
    Invalid input. Not an integer.

    Enter a non-negative integer: -42
    You entered -42

    Don't panic!

    Goodbye for now.



    Cheers!

    Z

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

    jace5869 (November 3rd, 2012)

  4. #3
    Junior Member
    Join Date
    Nov 2012
    Posts
    5
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Need help with simple calc java program

    We haven't covered exception handling yet, but at one point I did have the input received as a string and then Integer.parseInt(). I think I still received some type of error from that. Anyway I can use the try/catch and return it back to the loop after displaying an error message?

  5. #4
    Member
    Join Date
    Jun 2012
    Location
    Left Coast, USA
    Posts
    451
    My Mood
    Mellow
    Thanks
    1
    Thanked 97 Times in 88 Posts

    Default Re: Need help with simple calc java program

    Quote Originally Posted by jace5869 View Post
    We haven't covered exception handling yet
    A lot of "starter" programs do things the simplest possible way and leave the "Good Stuff" for later.
    Quote Originally Posted by jace5869 View Post
    ...at one point I did have the input received as a string and then Integer.parseInt(). I think I still received some type of error from that.
    Yes, parseInt() is what throws the exception.
    Quote Originally Posted by jace5869 View Post
    Anyway I can use the try/catch and return it back to the loop after displaying an error message?
    I think that's what my example illustrated. At least that's what I had in mind with the "123This can't be good, can it?" user input that I showed.

    Bottom line: If you haven't covered exceptions but your program is supposed to handle invalid input, you can read into a String and then go through the String character-by-character (in a loop) to verify they are all decimal digit characters and then call parseInt() if they are.


    Or some such thing.

    Cheers!

    Z

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

    jace5869 (November 3rd, 2012)

  7. #5
    Junior Member
    Join Date
    Nov 2012
    Posts
    5
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Need help with simple calc java program

    Thanks for the help. We haven't covered exception handling yet, and I received a response from the instructor saying it's okay as is.

Similar Threads

  1. Need help with simple calc java program
    By jace5869 in forum What's Wrong With My Code?
    Replies: 1
    Last Post: November 2nd, 2012, 11:51 PM
  2. ::: Write a Simple Java Program :::
    By riyaju in forum Object Oriented Programming
    Replies: 3
    Last Post: July 27th, 2012, 09:04 AM
  3. Simple Java Program
    By Robbiep in forum What's Wrong With My Code?
    Replies: 6
    Last Post: October 24th, 2011, 07:27 AM
  4. PLEASE HELP!!!! simple java program...
    By parvez07 in forum Object Oriented Programming
    Replies: 5
    Last Post: August 26th, 2009, 06:38 AM
  5. help with simple java program
    By parvez07 in forum Java Theory & Questions
    Replies: 4
    Last Post: August 25th, 2009, 07:19 AM