How do I loop this?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Crosson
    New Member
    • Sep 2010
    • 12

    How do I loop this?

    Here is my code:

    Code:
      
        System.out.println("Please enter the number you think the die will roll. The number must be between 1 and 6");
        for (boolean numRun=true; numRun;) {
                Scanner sc = new Scanner(System.in);
                if (sc.hasNext()) {
                    numInput = sc.nextInt();
                    if (numInput >= 1 && numInput <= 6) {
                        numRun= false;
                        System.out.println("The number you have entered is between 1 and 6");
                    } else {
                        System.err.println("You have entered an incorrect value.");
                        numRun=true;
                        
                    }
                }
        }
    How do i write the code so that it keeps asking the same questions until the value the user entered is in the 1 to 6 parameters?
  • Rabbit
    Recognized Expert MVP
    • Jan 2007
    • 12517

    #2
    Use a while loop instead of a for loop.

    Comment

    • Crosson
      New Member
      • Sep 2010
      • 12

      #3
      okay i changed the code a little bit:
      Code:
          System.out.println("Please enter the number you think the die will roll. The number must be between 1 and 6");
          for (boolean numRun=true; numRun;) {
              Scanner sc = new Scanner(System.in);
      
              int numInput = sc.nextInt();
              if(numInput >= 1 && numInput <= 6) {
                  int number = numInput;
                  numRun = false;
              } else {
                  System.out.println("The # you entered is not between 1 and 6. Please re-enter a number.");
                  numRun = true;
              }
          }
          System.out.println(number);
      And I think the loop will work fine, but what my problem is that the variable number cannot be found outside of the loop. How do i get the variable outside the loop?

      Comment

      • Rabbit
        Recognized Expert MVP
        • Jan 2007
        • 12517

        #4
        Declare the variable outside the loop

        Comment

        • Crosson
          New Member
          • Sep 2010
          • 12

          #5
          i declared the variable 'number' outside the loop ... but now my program is saying the the variable might not have been initialized

          Comment

          • Rabbit
            Recognized Expert MVP
            • Jan 2007
            • 12517

            #6
            Initialize it to 0

            Comment

            • Crosson
              New Member
              • Sep 2010
              • 12

              #7
              thanks for the help !

              Comment

              Working...