+ 1
Choosing in Java
Hey, I want to make a program where you will be able to choose from two options one, and in the case of an incorrectly selected check mark, the program is to ask us to provide data again. How to do it? I have done so much so far. {...} this sign means that the code is there, you should not worry about it. public class Main { public static void main(String[] args) { System.out.println(" Enter 1 if you want to choose calculator, or 2 if you want to choose an encryption program."); Scanner inputchoice=new Scanner(System.in); int choice = inputchoice.nextInt(); //calculator if(choice==1) {...} //encryption program if(choice==2) {...} //error else { System.out.println(" Please enter a valid value."); } } }
3 Answers
+ 1
In this case, i'd use the switch statement.
input = inputchoice.nextInt();
switch(input){
case 1:
calculator();
break;
case 2:
Encryption();
break;
default:
throw new ApplicationError("bad input!");
}
+ 1
I also did it that way:
int choice = 0;
do {
Scanner inputchoice = new Scanner(System.in);
choice = inputchoice.nextInt();
//calculator
if (choice == 1)
//encryption program
if (choice == 2)
}
while (choice < 1 || choice > 2);
}
0
Has the problem been solved?
If not then kindly try doing this else ignore.
while(true) {
if(choice==1) {
// calculator
break;
}
else if(choice==2) {
// encryption program
break;
}
else {
System.out.println(" Please enter a valid value.");
choice = inputchoice.nextInt();
}
}