here is the Menu class
import java.util.Scanner;
public class Menu {
private String[] menu_options;
public Menu(String[] menu_options) {
this.menu_options = menu_options;
}
public int getUserInput() {
int i = 1;
for (String s : this.menu_options) {
System.out.println(i + ". " + s);
i++;
}
int selection = getint_input(menu_options.length);
return (selection);
}
private int getint_input(int max) {
boolean run = true;
int selection = 0;
while (run) {
System.out.print("Select an option: ");
Scanner in = new Scanner(System.in);
if (in.hasNextInt()) {
int value = in.nextInt();
if(value>=1 || value<=max){
selection = value; //fixed this now working
run = false;
}
} else {
System.out
.print("Invalid input. Please enter a integer between 1 and "
+ max + ": ");
}
}
return selection;
}
}
and here is the menudriver i was using
public class Menutester {
public static void main(String[] args) {
String[] menuitems = new String[2];
menuitems[0] = "option one";
menuitems[1] = "option two";
Menu tm = new Menu(menuitems);
int choice = tm.getUserInput();
System.out.println("Got input");
}
}
the first time i input something it dosn’t regester at all and when i try to debug it in eclipse it gives me the error FileNotFoundException(Throwable).(String) line: 195 on the first input.
this is what it returns
- option one
- option two
Select an option: 1(i entered this and pressed enter)
1(same here only it regestered the input)
Got input
nextIntreads the input and removes it from the buffer. You can’t call it like that without storing the value.Call it once, store the value, and then do all the checks needed.
Change this:
for this: