-1

I have been trying to implement a function that returns an int from 0 to range. I have implemented the code to get an integer in the first place put don't know how to loop this in with the range part.

    public int get_input_int(int range){
    Scanner int_reader = new Scanner(System.in);
    String current_input = int_reader.next();
    while(!int_reader.hasNextInt()){
        current_input = int_reader.next();
    }
    if(Integer.valueOf(current_integer) > 0 && Integer.valueOf(current_integer) < range){
        return current_input
    }
    return current_input;
}
Mayneman
  • 13
  • 1
  • 3
  • What is `current_integer` refers to? – Blasanka May 21 '17 at 04:51
  • Does my answer below suit your needs? If so, please accept it. Thank you! (it is [here](https://stackoverflow.com/questions/44092874/java-scanner-to-accept-range-of-integer-values/44092916#44092916)) –  May 25 '17 at 05:21

2 Answers2

1

Please follow Java naming conventions (camel case, not _). I would prefer to pass the Scanner into the method. Also, you might as well consume an int (after checking for one). Something like,

public int getInputInt(Scanner in, int range) {
    while (in.hasNext()) {
        if (in.hasNextInt()) {
            int val = in.nextInt();
            if (val >= 0 && val < range) { // <-- from "0" to "range".
                return val;
            }
        } else {
            in.next();
        }
    }
    return -1;
}
Elliott Frisch
  • 183,598
  • 16
  • 131
  • 226
0

You have to use nextInt() rather than next(). next() is use for Strings, whereas nextInt() is for numbers. Also, declare current_input as an int rather than a String. Your program is way over-complicated also. Your program can simply look like this:

public int getIntInput(int range) {
    Scanner intReader = new Scanner(System.in);
    int currentInput = intReader.nextInt();
    if(currentInput > 0 && currentInput < range){
        return currentInput;
    }
}