AC Guns AC Guns - 6 months ago 55
Java Question

is this code for parsing from string method to integer answer ok?

So I'm making a programme in java for a college assignment.

in my main menu i have a choice option that a user can choose from 1-7 and to validate that I created this

public static String validateChoice(int floor, int roof) { // method for validating user input. floor = lowest possible value user can input & roof is maximum possible value user can input
int choice = -1;
String errorMessage = "Error: only numbers between " + floor + " and " + roof + " are accepted";

while(true) { // keeps looping until valid choice number is met
while(!intScanner.hasNextInt()) { // will keep looping if user doesn't input an int e.g user inputs string
intScanner.next(); // if user inputs string then eat that up and print error message and loop again
System.out.println(errorMessage);
}
choice = intScanner.nextInt();

if(choice >= floor && choice <= roof) // if choice is inbetween floor and roof
return Integer.toString(choice); // return that value parsed as a string (cause this method is string)
else
System.out.println(errorMessage);

}
}
System.out.println(errorMessage);


and that is returned into this

choice = Integer.parseInt(validateChoice(floor, roof));


My question is, is it ok to parse from a string method to an int variable. I'll admit i'm fairly ignorant in java so I would like your opinions on whether it's a good idea to write programmes like that. My thought process was is like it's two birds with one stone. It validates ints and returns an error when user input is wrong in one method

Answer Source

This seems like a poor idea, just return the int. Converting to a String isn't free. Parsing a String back to an int isn't free, and your method could easily return an int.

As I said, just return the int.

public static int validateChoice(int floor, int roof) {
    String errorMessage = "Error: only numbers between " + floor 
            + " and " + roof + " are accepted";
    while (true) {
        while (!intScanner.hasNextInt()) {
            intScanner.next();
            System.out.println(errorMessage);
        }
        int choice = intScanner.nextInt();
        if (choice >= floor && choice <= roof) {
            return choice;
        }
        System.out.println(errorMessage);
    }
}

And then, to use it,

choice = validateChoice(floor, roof);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download