Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 10 of 10
  1. #1
    New to the CF scene
    Join Date
    Nov 2008
    Posts
    7
    Thanks
    5
    Thanked 0 Times in 0 Posts

    adding a menu loop to existing program

    I have to add the following loop to the current code. I am learning methods, and don't know how to go about this problem. Any hints or advice to further my learning would be greatly appreciated.

    1. convert to kilometers
    2. convert to inches
    3. convert to feet
    4. quit the program.

    Thanks.

    Code:
    import java.util.Scanner; //needed for scanner class
    
    /**
    	
    	Java Thursday Evening
    
    */
    
    public class convertingMetersMethod
    {
    	
    
    	public static void main(String [] args)
    	{
    
    		int number;	//number entered by user
    		double meters;
    
    
    
    	// create a scanner object for keyboard input
    	Scanner keyboard = new Scanner(System.in);
    
    
    
    	//enter meters
    	System.out.println("Enter a distance in meters: ");
    	meters = keyboard.nextDouble();
    
    
    
    	// get a selection from menu
    	System.out.print("Enter your choice: ");
    	System.out.println("\n1. Convert to kilometers\n2. Convert to inches\n" +
    							 "3. Convert to feet\n4. Quit the program");
    	number = keyboard.nextInt();
    	
    
    	//determine number entered
    	switch (number)
    	
    	{
    	
    		case 1:
    			showKilometers(meters);
    			break;
    
    		case 2:
    			showInches(meters);
    			break;
    
    		case 3:
    			showFeet(meters);
    			break;
    
    		case 4:
    			System.out.println("Thanks.  Good day!");
    			System.exit(0);
    
    		default:
    			System.out.println("That's not a valid option, try again: ");
    			number = keyboard.nextInt();
    	}
        }
    	
    	public static void showKilometers(double meters)
    	{
    		double kiloMeters;
    			kiloMeters = meters * 0.001;
    			System.out.println(meters + " meters is " + kiloMeters + " kilometers.");
    			
    				}
    	
    	public static void showInches(double meters)
    	{
    		double inches;
    			inches = meters * 39.37;
    			System.out.println(meters + " meters is " + inches + " inches.");
    			
    	}
    	
    	public static void showFeet(double meters)
    	{
    		double feet;
    			feet = meters * 3.281;
    			System.out.println(meters + " meters is " + feet + " feet.");
    			
    	}
    }

  • #2
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,987
    Thanks
    4
    Thanked 2,660 Times in 2,629 Posts
    This doesn't require a method, you simply need a loop for it.
    I would actually change you're setup and ask first what they want to do, then ask what the length is. This is for simplicity so they can more easily exit the program.
    Code:
    do
    {
    	System.out.print("Enter your choice: ");
    	System.out.println("\n1. Convert to kilometers\n2. Convert to inches\n" +
    							 "3. Convert to feet\n4. Quit the program");
            
    	number = keyboard.nextInt();
            ... // All you're processing here
    } while (number != 4);
    I would probably fetch a next or nextline out of the scanner and use that in the while condition as well, or try/catch a nextInt (I believe it will throw an InputMisMatch exception, but remember that Exception sweeps all).
    Code:
    boolean bKeepGoing = false;
    do
    {
        bKeepGoing = false;
        .. Scanner stuff
        try
        {
            number = keyboard.nextInt();
        }
        catch (Exception ex)
        {
            System.out.println("Incorrect choice, please try again...\n");
            bKeepGoing = true;
        }
    } while (bKeepGoing || number != 4);
    Now you can keep asking them to try again. You can also map number != 4 to keepGoing to just use a single variable.

    If you set it up with a couple of loops, you can do simple things quite easily. A logical algorithm for this is something like:

    Code:
    do
      keepGoing <-- false
      getChoice from choices
      if try int cast getChoice throws
        keepGoing <-- true
      otherwise
        do
          getDistance <-- keyboard
        while getDistance is not number // Same method as above, try/catch it
        // Perform requested action
    while keepGoing or getChoice is not exit
    Another option would be to break you're inputs up into methods, and pass them back and forth (kinda like ping pong) until the user asks to exit. The loop is easier since its more readable to do.
    PHP Code:
    header('HTTP/1.1 420 Enhance Your Calm'); 

  • Users who have thanked Fou-Lu for this post:

    jlopez3203 (11-11-2008)

  • #3
    New to the CF scene
    Join Date
    Nov 2008
    Posts
    7
    Thanks
    5
    Thanked 0 Times in 0 Posts
    Thanks for all the information. I would like to see what separating them into methods would look like, since I believe that's what the professor would like us to do.

    Thanks again for all your help.

  • #4
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,987
    Thanks
    4
    Thanked 2,660 Times in 2,629 Posts
    This is for a class?
    We really shouldn't be giving you code in that situation. If this is an introductory java class I can't see them wanting you to use methods to ping pong requests back and forth. Its too confusing to do that.
    Logically, you would do like so. From you're main you would call a choice method. If the choice method receives an invalid choice, it recalls the choice function. Otherwise it calls the appropriate method for processing. The methods all end in calling the choice method.
    Not only is it not really reusable, it also uses recursion. I can't see this being what an instructor is looking for. Looping algorithms is likely what they are looking to do.

    Edit:
    What I can see is the instructor wanting the choice menu to be displayed from a method. You would then loop it in you're main menu to process. This makes sense since an extension object could implement a gui on top of it by overriding the menu method.
    Last edited by Fou-Lu; 11-11-2008 at 10:54 PM.
    PHP Code:
    header('HTTP/1.1 420 Enhance Your Calm'); 

  • Users who have thanked Fou-Lu for this post:

    jlopez3203 (11-12-2008)

  • #5
    New to the CF scene
    Join Date
    Nov 2008
    Posts
    7
    Thanks
    5
    Thanked 0 Times in 0 Posts
    I am taking a course for Java, correct. I am not asking for code, code is appreciated, but as you left code for me earlier to look at, I can't really turn that in and get full credit, Being we are not at that stage yet, the instructor would really wonder where I came up with that code, and if he asks me about it, I wouldnt know the answer to why, or how it works, which would impede my learning. I dont want an easy meal ticket by coming on here, I want to learn, and would like to get as much help as people out there are willing to offer.

    I could have posted my whole assignment on here and expect someone to do it for me. Java is one of those subjects where you have to see it to understand it. I can post all the code I am doing and have people like yourself who are very knowledgeable just keep correcting, but to me that would seem futile and more of a burden to the board. I do get help from instructor, I stay later than the other classmates getting help. Thats only once a week, being I work 40 hours a week, can't really spend all day in a classroom environment, so Im trying to do the best I can with the resources possible. This being one of them.

    Everyone on here has been very helpful, including yourself, Fou-Lu. I am very appreciative of all your help. If there were anything I could do to return the favor I would...or will.

    My assigment is to create a program that converts meters into kilometers, inches, and feet, to create a method for each one, and an extra method for the menu that should NOT ACCEPT ANY ARGUMENTS (what does that mean?)

    The way I approached it was to create a loop for the program, got that working, broke up the code into methods, had a problem, which I posted for help and got it, thanks again for that. Now I can't do the menu portion, I tried doing it, but I get an infinite loop. Which is the last thing I need to complete my assigment, which is late, because I do struggle, but am trying.

    Code:
    import java.util.Scanner; //needed for scanner class
    
    /**
    	Java Thursday Evening
    
    */
    
    public class convertingMetersMethodmenuloop
    {
    	
    
    	public static void main(String [] args)
    	{
    
    		int number;	//number entered by user
    		double meters;
    
    
    
    	// create a scanner object for keyboard input
    	Scanner keyboard = new Scanner(System.in);
    
    
    
    	//enter meters
    	System.out.println("Enter a distance in meters: ");
    	meters = keyboard.nextDouble();
    
    
    
    
    do
    {
    	System.out.print("Enter your choice: ");
    	System.out.println("\n1. Convert to kilometers\n2. Convert to inches\n" +
    							 "3. Convert to feet\n4. Quit the program");
            
    	number = keyboard.nextInt();
           
    
    
    	//determine number entered
    	switch (number)
    	
    	{
    	
    		case 1:
    			showKilometers(meters);
    			break;
    
    		case 2:
    			showInches(meters);
    			break;
    
    		case 3:
    			showFeet(meters);
    			break;
    
    		case 4:
    			System.out.println("Thanks.  Good day!");
    			System.exit(0);
    
    		default:
    			System.out.println("That's not a valid option, try again: ");
    			number = keyboard.nextInt();
    	}
      } while (number != 4);  
    	 }
    	
    	public static void showKilometers(double meters)
    	{
    		double kiloMeters;
    			kiloMeters = meters * 0.001;
    			System.out.println(meters + " meters is " + kiloMeters + " kilometers.");
    			
    				}
    	
    	public static void showInches(double meters)
    	{
    		double inches;
    			inches = meters * 39.37;
    			System.out.println(meters + " meters is " + inches + " inches.");
    			
    	}
    	
    	public static void showFeet(double meters)
    	{
    		double feet;
    			feet = meters * 3.281;
    			System.out.println(meters + " meters is " + feet + " feet.");
    			
    	}
    }

  • #6
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,987
    Thanks
    4
    Thanked 2,660 Times in 2,629 Posts
    The method with no arguments is simply a method like so:
    Code:
    public [static] void showMenu() // <-- No parameters, refers to what goes in the ()
    {
    }
    
    public [static] void showMenu(Object obj) // <-- Parameter obj
    Static is optional depending on if you are treating it as an object or a class method. If you haven't learned objects than static is what you'll be using (and makes sense with the rest of you're code).
    Depending on if you're expecting to return a value depends on the actual signature, and how it would be handled in you're main method. I would say that if you're signature is to return void, that the looping should take place inside of you're show menu (which also means you would have you're processing calls within that as well). If you are to return an integer value, I'd say the method's job is to use scanner to retrieve input and return the chosen result for the main method to loop and process (I'd bet this is what you're supposed to do).
    I copy and pasted the code. It works fine, as long as integer values are chosen (I'm guessing you're using eclipse or dr java or another similar program, try increasing the size of you're console window).
    It prompts first to enter a number for the meters, then asks me what to do with the number. After telling it what you want it to do it displays the result and asks again what I want to do.

    Now, you mentioned things you haven't learned. Assuming that you haven't covered objects yet, I'd bet its safe to guess its try/catching with exception trapping that you haven't covered yet? If thats the case, there really isn't an easy way to do this. Since any string to number throws an exception on cast (if its invalid) you can't determine if its a valid number in advance. You could do it with you're menu since its limited in options, but not with the meter choice input.

    Otherwise, like I said this is working fine. Post back with how you want to handle the menu method (as in, do you want it to completely process within that method, or do you want the main to do it) and I'll show you how to change it from what you have.
    PHP Code:
    header('HTTP/1.1 420 Enhance Your Calm'); 

  • #7
    New to the CF scene
    Join Date
    Nov 2008
    Posts
    7
    Thanks
    5
    Thanked 0 Times in 0 Posts
    Thanks for your post.

    The output is suppose to look like this:
    Code:
    Enter a distance in meters:  500 [Enter]
    
    
    1. Convert to kilometers
    2. Convert to inches
    3. Convert to feet
    4. Quit the program
    
    Enter your choice: 1 [Enter]
    500 meters is 0.5 kilometers.
    
    1. Convert to kilometers
    2. Convert to inches
    3. Convert to feet
    4. Quit the program
    
    Enter your choice: 3 [Enter]
    500 meters is 1,640.5 feet.
    
    1. Convert to kilometers
    2. Convert to inches
    3. Convert to feet
    4. Quit the program
    
    Enter your choice: 4 [Enter]
    Bye!
    Im thinking of creating a method like so: (just my menu loop)

    Code:
    public class convertingMetersMethodmenuloopmenu
    {
    	
    
    	public static void main(String [] args)
    	{
    
    		int number;	//number entered by user
    		double meters;
    
    
    
    	// create a scanner object for keyboard input
    	Scanner keyboard = new Scanner(System.in);
    
    
    
    	//enter meters
    	System.out.println("Enter a distance in meters: ");
    	meters = keyboard.nextDouble();
    
    
    	
    		System.out.print("Enter your choice: ");
    		number = keyboard.nextInt();
    		
    
    }
    
    public static void Menu(int number, double meters)
    {
    do
    {
    	
    	System.out.println("\n1. Convert to kilometers\n2. Convert to inches\n" +
    							 "3. Convert to feet\n4. Quit the program");
            
      } while (number != 4); 
    
    public.......Kilometers......
    I want the inputs to be moved up to the previous method, I want the first method to hold all the input, but somehow I have to add a menu inbetween. I dont think the menu holds any info except a loop and the ability to stop at number = 4.

    Code:
    //so crudely put;
    
    main method
    
       method input // number and meters
    
       method menu // loop for menu only accepts 4 to stop loop
    
       method kilometers // calculate
    
      method feet // calculate
      
      method inches. // calculate
    Can it be done that way?

    thats how I think it should be broken down, but dont know how to make sense or make it work that way...Or maybe a need a preloop so it can run the menu after meters input, then another to kick in when the number of menu selection is typed in.

    We are using Jgrasp as the compiler and to run the program we are doing.

    Thanks so much....

  • #8
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,987
    Thanks
    4
    Thanked 2,660 Times in 2,629 Posts
    You could do something like that, but you mentioned a method signature before that took no arguments. For that reason, I'm thinking that you return a result instead, so it would just be the menu display and fetching the value:
    Code:
        public static int showMenu()
        {
            int iResult = 0;
            System.out.println("\n1. Convert to kilometers\n" + 
                            "2. Convert to inches\n" +
                            "3. Convert to feet\n4. Quit the program");
            System.out.print("\nEnter your choice: ");
            iResult = new Scanner(System.in).nextInt();
            return iResult;
        }
    This is because if you are not allowed to use an argument for it, you cannot pass in the number of meters that was specified (and hereby call you're desired processing methods).
    You would implement it back into you're main:
    Code:
    public static void main(String[] args)
    {
        double dMeters;
        int iChoice;
        System.out.print("Enter a distance in meters: ");
        dMeters = new Scanner(System.in).nextDouble();
    
        do
        {
            iChoice = showMenu();
            // do you're switching and processing
        }
        while (iChoice != 4);
    }
    Something like that. This is how I would go abouts the problem.
    The only real change I'd do is remove the exit call from the switch case 4 and replace it with a break. Then I'd run an exit call at the end of the entire main method (just in case something goes wrong). Next to that, remove the fetch for the nextInt out of the default case - since the value is not 4 it will loop again and present the user with the menu. But I guess that depends on what you want to do with it, it will be problematic if you don't do it that way (it would prompt the user twice for data, but there is a way to get around that as well).

    Once you're using objects this will become easier - you can access data throughout the entire object where you can more easily adapt the original looping idea that you had for you're menu (since you don't require parameters to be passed into it).
    PHP Code:
    header('HTTP/1.1 420 Enhance Your Calm'); 

  • #9
    New to the CF scene
    Join Date
    Nov 2008
    Posts
    7
    Thanks
    5
    Thanked 0 Times in 0 Posts
    This is what I came up with, but two things..

    1. the menu doesnt appear when asking for meters
    2. after it loops one time then it starts appearing, meaning person will have to make a choice blindly the first time...

    I dont have the layout like the professor wants it either, he asks for a choice then it gives him the result right under, my program, the result goes under the menu. That should be a quick fix, or not?

    Code:
    import java.util.Scanner; //needed for scanner class
    
    /**
    	Java Thursday Evening
    
    */
    
    public class convertingMetersMethodmenuloopmenu
    {
    	
    
    	public static void main(String [] args)
    	{
    
    		int number;	//number entered by user
    		double meters;
    
    
    
    	// create a scanner object for keyboard input
    	Scanner keyboard = new Scanner(System.in);
    
    
    
    	//enter meters
    	System.out.println("Enter a distance in meters: ");
    	meters = keyboard.nextDouble();
    
    
    	
    		System.out.print("Enter your choice: ");
    		number = keyboard.nextInt();
    		
    
    }
    
    public static void Menu(int number, double meters)
    {
    do
    {
    	System.out.println("\n1. Convert to kilometers\n2. Convert to inches\n" +
    							 "3. Convert to feet\n4. Quit the program");
            
      } while (number != 4); 
           
    
    
    	//determine number entered
    	switch (number)
    	
    	{
    	
    		case 1:
    			showKilometers(meters);
    			break;
    
    		case 2:
    			showInches(meters);
    			break;
    
    		case 3:
    			showFeet(meters);
    			break;
    
    		case 4:
    			System.out.println("Thanks.  Good day!");
    			System.exit(0);
    
    		default:
    			System.out.println("That's not a valid option, try again: ");
    			number = keyboard.nextInt();
    	}
     
    	 }
    	
    	public static void showKilometers(double meters)
    	{
    		double kiloMeters;
    			kiloMeters = meters * 0.001;
    			System.out.println(meters + " meters is " + kiloMeters + " kilometers.");
    			
    				}
    	
    	public static void showInches(double meters)
    	{
    		double inches;
    			inches = meters * 39.37;
    			System.out.println(meters + " meters is " + inches + " inches.");
    			
    	}
    	
    	public static void showFeet(double meters)
    	{
    		double feet;
    			feet = meters * 3.281;
    			System.out.println(meters + " meters is " + feet + " feet.");
    			
    	}
    }
    I get this error now that I try to run it, I modified the Menu loop....Am I close?

    Code:
    convertingMetersMethodmenuloopmenu.java:71: cannot find symbol
    symbol  : variable keyboard
    location: class convertingMetersMethodmenuloopmenu
    			number = keyboard.nextInt();
    			         ^
    1 error
    Question about your code, iResult, I think thats how he wants us to use, because he lectured about @Return, but how would you use iResult in my code? I tried adding it but got 14 errors...

    Hope I get this by tomorrow....Feel like Im doing worse than better.

  • #10
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,987
    Thanks
    4
    Thanked 2,660 Times in 2,629 Posts
    Whew, what a day :P
    Lessee what you got here.
    Ok, the main reason why it won't work (logically) is because you're never calling the Menu method.
    Next, you're syntax error you're receiving is because Scanner hasn't been initialized within you're Menu method (its whining about a lookup off of keyboard, when keyboard hasn't been declared).
    Once thats been fixed up, that still won't solve you're problem. The while loop you have isn't logical, in that it just continuously asks for input until it gets a four and its only process from that point is to exit. Number (as in you're variable called number) is also worth mentioning. The usage here would be a pass by reference usage, and to do that in java you would need to use a primitive wrapper class (if you haven't learned about these, then you can't do the reference).
    When you execute a function or method (used interchangeably, though they are technically different I suppose), you create whats called a function stack. This is hard to explain if you're new to programming, but I'll give it a shot anyway. A variable is simply a location pointed to in memory. When you pass this variable into a function it takes a copy of it unless its of type object (in java, this isn't the same in every language). So any object that extends object (which is any object) is passed by reference. The difference is, when you change the value of you're variable. If its a pass by value, it only changes the value while its on the current stack, and is destroyed once the stack is popped. A reference though points at the same memory location as the original variable so when you change the value, it changes it in the main as well.

    To use the loop in you're menu, follow this algorithm:
    Code:
    static sub Menu (double dMeters, Scanner keyboard)
    int iChoice <-- 0 // The chosen number
    do
        Display menu
        iChoice <-- keyboard.nextInt()
        switch iChoice
            case 0:
                .... // And so forth.
    while iChoice != 4
    Do you're do/while needs to surround you're entire processing block. You want to do this so that the user can keep selecting operations on their input meters until they choose to exit. You're menu method actually only requires one paramter, dMeters which is the original meters the user specified. This is required since you would need to pass it into you're operating functions. If you do only the one argument, you'll need to initialize a new scanner inside you're main method.

    When you're doing this as an object, it will be a lot easier.
    Code:
    public class MeterConverter
    {
        private double dMeters;
        public MeterConverter()
        {
             this(0);
        }
        public MeterConverter(double dMeters)
        {
            this.dMeters = dMeters;
        }
        public double toKM()
        {
            return this.dMeters * 0.001;
        }
        public double toInches()
        {
            return this.dMeters * 39.37;
        }
        public double toFeet()
        {
            return this.dMeters * 3.281;
        }
    }
    Lots and lots easier. Mind you this doesn't have anything for its main menu so it would still be long, but the actual code is simple since you've got global access to you're properties within you're object.


    Oh, and as for you're formatting, its all a matter of System.out.println versus System.out.print. One adds a line feed while the other does not. Simple as that.
    PHP Code:
    header('HTTP/1.1 420 Enhance Your Calm'); 

  • Users who have thanked Fou-Lu for this post:

    jlopez3203 (11-13-2008)


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •