0

I'm having troubles with the output of my program. I've developed the class 'GetInput' as a constructor which I can reuse when asking various questions for input. Each question asked will need to be equal to or more than a minimum/less then a maximum number which is passed on to the class/constructor. The problem I have is that when the while loop is run, it asked for input four times before finally returning the correct value.

I've added flags which I've worked out when they display. The first shows after input is added the first time. Then the second time, then the fourth time. The fourth time it also displays the flag 'the end' which I want it to reach in one iteration. Why is it looping four times before finally correctly returning the value?

Thanks so much in advance. This is only my second day learning java and this is driving me insane.

import java.util.Scanner; //Import the scanner class

public class main {
public static void main(String[] args) {

    //Set variables to hold the entry cost for each category
    int costAccChild = 2;
    int costUnaccChild = 5;
    int costAdult = 10;
    int costSenior = 8;

    int test = GetInput(0, 1, "Enter a group? (Yes=1/No=0)");
    System.out.println(test);
    System.out.println("the end");

}

 static int GetInput(int min, int max, String request){     
    boolean inputValid = false; //Sets default value to variable for while loop
    int userInput = 0; //Sets default variable for input return

    while (inputValid == false) { //Loops until receives correct input
        System.out.println(request); //Prints question asking for input
        Scanner inputFromUser = new Scanner(System.in); //Ask user for input
        System.out.print("First time"); //FLAG DISPLAYS AFTER FIRST SCANNER

        if (inputFromUser.hasNextInt() == true){ //Check if input has an integer

            System.out.print("Second Time"); //FLAG SHOWS AFTER SECOND SCANNER

            if (inputFromUser.nextInt() >= min && inputFromUser.nextInt() <= max ){ //Check if input is valid
                userInput = inputFromUser.nextInt();
                inputValid= true;

                System.out.print("Fourth time"); //FLAG WORKS FORTH TIME

            }else{ //Input is not correct integer, give error message
                System.out.println("Input is not valid");           
                }   

        }else{ //Input is not an integer at all, give error message
            System.out.println("Input is not valid");
        }
    }
    return userInput; //Returns valid input
    }
}
1
  • Try using the eclipse debugger and understand your program Commented Mar 19, 2013 at 11:14

2 Answers 2

2

From the manual page http://docs.oracle.com/javase/6/docs/api/java/util/Scanner.html#hasNextLong() :

Both hasNext and next methods may block waiting for further input

It didn't loop 4 times, but whenever you say inputFromUser.hasNextInt() or inputFromUser.nextInt() the Scanner actually blocks waiting for you to input a value.

So this is obviously a bug you have to fix

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for the quick reply. Any suggestions for how to fix this bug? When you say further input is blocked, what exactly does that mean?
It means your program will stop executing and wait until data is available on the stream (ie: wait until you press something on the console and hit enter)
Ah, I understand now, although it makes little sense to me. Should I be turning the scanner off after I get input? Or perhaps is there another statement I can use instead? I'm new to programming and only just started learning Java yesterday so apologies if I'm a hassle to explain to.
Thanks for the answer, I looked into it more and both cleaned it up and fixed the program. It's working perfectly now.
0

You should store input in some variable and then compare them in the if condition.

This will not block input for further input.

Try this:

public static void main(String[] args) {

    //Set variables to hold the entry cost for each category
    int costAccChild = 2;
    int costUnaccChild = 5;
    int costAdult = 10;
    int costSenior = 8;

    int test = GetInput(0, 1, "Enter a group? (Yes=1/No=0)");
    System.out.println("Return Result: " + test);
    System.out.println("The end");

}

static int GetInput(int min, int max, String request) {
        boolean inputValid = false; //Sets default value to variable for while loop
        int userInputMin = 0, userInputMax=0; //Sets default variable for input return

        while (inputValid == false) { //Loops until receives correct input
            System.out.println(request); //Prints question asking for input
            Scanner inputFromUser = new Scanner(System.in); //Ask user for input
            System.out.print("First time: "); //FLAG DISPLAYS AFTER FIRST SCANNER

            if (inputFromUser.hasNextInt() == true) { //Check if input has an integer
                userInputMin = inputFromUser.nextInt();
                System.out.print("Second Time: "); //FLAG SHOWS AFTER SECOND SCANNER
                if (inputFromUser.hasNextInt() == true) { //Check if input has an integer
                    userInputMax = inputFromUser.nextInt();
                    if (userInputMin >= min && userInputMax <= max) { //Check if input is valid

                        inputValid = true;

                        System.out.println("Third time"); //FLAG WORKS Third Time

                    } else { //Input is not correct integer, give error message
                        System.out.println("Input is not valid");
                    }
                }    
            } else { //Input is not an integer at all, give error message
                System.out.println("Input is not valid");
            }
        }
        return userInputMin; //Returns valid input
    }  

6 Comments

That almost fixes it, it only iterates twice now instead of four times.
It depends on what values you enter ? What was input ?
Well the ideal input for the first question is either 1 or 0. Both of them cause the program to reach the 'second time' flag which I put in, but get no further. When I press enter again it finishes the loop as wanted
As gerrytan described to me, the program is not iterating, but instead pauses to wait for input (enter in the console) when I didn't want it to. After the initial scanner It still pauses between flag 2 and 3 waiting for input.
I've worked it out, thanks for the help, I understand what was happening now too!
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.