2

So, the user has to choose a number between 1 and 3. Otherwise, they're told to try again. If the user tries a number less than 1 or greater than 3, whatever number they chose gets stored in the "choice" variable and causes the program to continue to run when it should just stop. I assumed there would be an easy solution, but apparently it's beyond me as a beginner. The obvious thing to me would be to somehow clear or empty the value that has been assigned to "choice" after the unsuccessful user input. Is that possible?

import java.util.Scanner;

public class Furniture2Test  {

    public static void main(String[] args) {

        wood();

    } // end main

    public static void wood() {

        int choice;

        int pine = 1;
        int oak = 2;
        int mahogany = 3;

        int pineCost = 100;
        int oakCost = 225;
        int mahoganyCost = 310;

        Scanner keyboard = new Scanner(System.in);

        System.out.println("What type of table would you like?");
        System.out.println("1. pine");
        System.out.println("2. oak");
        System.out.println("3. mahogany");

        choice = keyboard.nextInt();

        if (choice == 1) {
            choice = pineCost;
        } else if (choice == 2) {
            choice = oakCost;
        } else if (choice == 3) {
            choice = mahoganyCost;
        } else if (choice > 3 || choice < 1) {
            System.out.println("Try again.");
            choice = -1;
            wood();
        }

        System.out.println("That will be $" + choice + ".");

        size(choice);

    } // end wood

    public static void size(int choice) {

        int sizeChoice;
        int large = 35;

        Scanner keyboard = new Scanner(System.in);

        System.out.println("What size will that be?");
        System.out.println("1. large");
        System.out.println("2. small");

        sizeChoice = keyboard.nextInt();

        if (sizeChoice == 1)
            System.out.println("That will be $" + (choice + large) + ".");
        else if (sizeChoice == 2)
            System.out.println("That will be $" + choice);
        else
            System.out.println("Please, enter either a 1 or a 2.");

    } // end size

}
Smit
  • 4,685
  • 1
  • 24
  • 28
user2817128
  • 21
  • 1
  • 2
  • 5
  • It's not entirely clear what you want. Exactly what are you asking? – luiscubal Sep 25 '13 at 22:17
  • 3
    Use a `do { ... } while ()` or `while()`. – Luiggi Mendoza Sep 25 '13 at 22:17
  • Why would you call `size(choice)` when the choice is obviously invalid...? – MadProgrammer Sep 25 '13 at 22:18
  • Thanks, Luiggi. I have no idea how to do that. Yes, I looked at examples, but they appear to be beyond my current level of understanding. – user2817128 Sep 25 '13 at 22:19
  • By the way, to handle these situations **do not** use a recursive call to the same method. – Luiggi Mendoza Sep 25 '13 at 22:20
  • MadProgrammer, `size(choice)` is being called only after the successful input. If the user enters an invalid number, an error message is displayed and `wood()` gets called again. The problem is that, at that point, `choice` has taken on two different values (e.g., 0 _and_ 1); if the user enters a wrong choice several times in a row, then `choice` apparently just keeps storing those values to use them later. – user2817128 Sep 26 '13 at 00:30
  • Luiggi, thank you for that advice. I'm not sure that I'd've been able to think of an alternative until presented with one by no_answer_not_upvoted. – user2817128 Sep 26 '13 at 00:34

5 Answers5

1

Your requirement can be done easily with do...while loop. Sample code is as follows:

do{
    System.out.println("Choose option between 1 and 3");
    choice = keyboard.nextInt();
}while(!(choice > 3 || choice < 1));

if (choice == 1) {
    choice = pineCost;
} else if (choice == 2) {
    choice = oakCost;
} else if (choice == 3) {
    choice = mahoganyCost;
}

Hope this helps.

SachinSarawgi
  • 2,632
  • 20
  • 28
0
//put the menu logic
while(choice > 3 || choice < 1) {
    //put your try again logic.
}
//can only exit the while loop if the number is 1, 2, or 3, so put your output statement down here after the while loop
nhgrif
  • 61,578
  • 25
  • 134
  • 173
  • Thanks, nhgrif. It may be that I didn't implement your suggestion correctly, but, when I tried this, I still had problems. – user2817128 Sep 25 '13 at 22:59
  • Can you post your code as it looks after implementing this? And explain what exactly the problem is now (assuming the problem is different)? – nhgrif Sep 25 '13 at 23:06
  • Well, looking at this again, I'm guessing that the problem is that I didn't understand your suggestion fully. I don't actually know how to work with "try logic" yet. I vaguely recall a try/catch function from a Visual Basic class I took, but I'm not sure I can see how or why I would use both a `while` and a `try/catch`. – user2817128 Sep 26 '13 at 00:14
  • Oh. Sorry, I wasn't suggesting that you implement a `try/catch` block or anything. The "try again logic" comment refers to the logic you had already coded to execute when the input was not 1,2, or 3. – nhgrif Sep 26 '13 at 00:38
0
import java.util.Scanner;

public class Furniture2Test

{

   public static void main(String[] args)
   {

      wood();

   } // end main


   public static void wood()
   {

      int choice;

      int pine = 1;
      int oak = 2;
      int mahogany = 3;

      int pineCost = 100;
      int oakCost = 225;
      int mahoganyCost = 310;

      Scanner keyboard = new Scanner(System.in);

      System.out.println("What type of table would you like?");
      System.out.println("1. pine");
      System.out.println("2. oak");
      System.out.println("3. mahogany");

      choice = read_range(keyboard, 1, 3);

      if(choice == 1)
      {
         choice = pineCost;
      }
      else
         if(choice == 2)
         {
            choice = oakCost;
         }
         else
            if(choice == 3)
            {
               choice = mahoganyCost;
            }
            else
               if(choice > 3 || choice < 1)
               {
                  System.out.println("Try again.");
                  choice = -1;
                  wood();
               }

      System.out.println("That will be $" + choice + ".");

      size(choice);


   }  // end wood

   public static void size(int choice)
   {

      int sizeChoice;
      int large = 35; 

      Scanner keyboard = new Scanner(System.in);

      System.out.println("What size will that be?");
      System.out.println("1. large");
      System.out.println("2. small");

      sizeChoice = read_range(keyboard, 1, 2);

      if(sizeChoice == 1)
         System.out.println("That will be $" + (choice + large) + ".");
      else
         if(sizeChoice == 2)
            System.out.println("That will be $" + choice);
         else
            System.out.println("Please, enter either a 1 or a 2.");

   } // end size

   private static int read_range (Scanner scanner, int low, int high) {
     int value;
     value = scanner.nextInt();
     while (value < low || value > high) {
       System.out.print("Please enter a value between " + low + " and " + high + ": ");
       value = scanner.nextInt();
     }
     return value;
   }



} // end class
necromancer
  • 23,916
  • 22
  • 68
  • 115
  • 1
    YOu just posted the code. What changes do you made are unclear. May be some explanation will be good.. – Smit Sep 25 '13 at 22:24
  • @Smit added and used `read_range(...)` method. hope that helps. – necromancer Sep 25 '13 at 22:25
  • I am not the one who wanted the answer. It should be clear enough so that whoever reads it, make sense to them and should be able to understand. – Smit Sep 25 '13 at 22:34
  • no_answer_not_upvoted, this seems to have fixed the problem. Thank you. I will surely have to look at your code for a while to figure out why it works, but your help is greatly appreciated. – user2817128 Sep 25 '13 at 22:36
  • @Smit i have made absolutely minimal changes, so a simple diff should be enough for the smart reader. the OP should be intimately familiar with her/his code and it should be easy to see what changed. – necromancer Sep 25 '13 at 22:55
  • @Smit verbiage and explanation are good when there the problem is worth it. this is a fairly matter-of-fact issue to be knocked off in a jiffy and get on with real stuff. see the discussion in, for instance: http://stackoverflow.com/questions/18921302/how-to-incrementally-sample-without-replacement – necromancer Sep 25 '13 at 22:57
  • no_answer_not_upvoted, you have done much more than I expected anyone to do. Your changes make the program run exactly as I intended it to. Thank you again. Incidentally, I would still love to know if it would've been possible to clear the value of "choice" after the `if(choice > 3 || choice < 1)`. – user2817128 Sep 25 '13 at 23:13
  • @user2817128 no, an int is 4 bytes of memory and each bit must be either a 0 or 1 so the collective 4 bytes must necessarily represent some number. they cannot be cleared. when you initially create the variable, those memory locations likely hold the value 0 however the java compiler will not compile a program that uses such an uninitialized value. IN SHORT: it does not make sense to clear an int variable; just don't use it. – necromancer Sep 25 '13 at 23:30
0

whatever number they chose gets stored in the "choice" variable and causes the program to continue to run when it should just stop//

the program is contining to run because you are calling wood() if(choice > 3 || choice < 1)

if you want it to stop remove the wood() call

if you also want to clear the value for choice(instead of -1) you can assign it to null

  • Well, my hope initially was that after I use `else if (choice > 3 || choice < 1)` I could then clear whatever value has then been stored in the "choice" variable (e.g., 0 or 4). However, I apparently can't just use `code choice = null;` or `code choice = clear();`. That's what I assumed would fix my problem and allow the program to loop back around to the beginning and start accepting input from the keyboard with nothing stored in memory. – user2817128 Sep 25 '13 at 22:55
0

choice is a local variable to the method wood, you are making a recursive call to wood when the user makes a wrong choice. This is an interesting design choice and probably not the best in this case.

When you call wood again, choice is rest (in this to unknown value until it is assigned value from the user).

Now the problem occurs when the wood method exists...each time it returns to the caller, it will call size(choice), where choice is -1 (because that's what you set it to before calling wood again).

  1. You should be using a while-loop instead of recursive calls
  2. You should never call size(choice) with anything other then a valid choice

Take a look at The while and do-while statement for more details

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • Thanks for your response, MadProgrammer. I'm not sure what you mean by "choice is rest." Actually, Looping is the next chapter I should be studying in the Java class I'm taking. At the moment, it seems beyond my level of understanding. – user2817128 Sep 25 '13 at 23:04
  • When you first enter the `wood` method, you declare the variable `choice`. This variable is assigned (by the JVM) and undefined value, until you assign a value from the user. It has no context beyond the current context of the method. So the next time you call the method, a new variable/pointer named `choice` is created. There is no relationship between the two... – MadProgrammer Sep 26 '13 at 00:03
  • I think I understand you now. Based on what you're saying, though, I would not expect the program to work when I give it the values that it wants. But, it does work in that case. For instance, if I choose "1" for the wood type, `choice` then takes on the value 100. That value is then passed into the `size` method. That part of the program is fine (well, from my admittedly limited perspective). However, for this assignment, I am supposed to ensure that the user cannot get to the `size` input if they don't enter a valid selection (i.e., a number between 1 and 3) for the wood type. – user2817128 Sep 26 '13 at 00:23