I need to display a menu with 2 options and ask the user to input an option.
I must validate the input: if the user puts anything other than "1" or "2" the program prints an error msg and ask them to put a new input.
import java.util.Scanner;
public class IndenteurPseudocode {
public static void main(String[] args) {
System.out.println("Ce programme permet de corriger l'indentation d'un algorithme ecrit en pseudocode.\n");
System.out.println("----");
System.out.println("Menu");
System.out.println("----");
System.out.println("1. Indenter pseudocode");
System.out.println("2. Quitter\n");
Scanner myObj = new Scanner(System.in);
String choixMenu;
boolean valid = false;
while(!valid) {
System.out.print("Entrez votre choix : ");
choixMenu = myObj.nextLine();
if ( choixMenu == "1" || choixMenu == "2") {
valid = true;
System.out.print(choixMenu);
} else {
System.out.println("invalid");
}
}
}
}
Run
Ce programme permet de corriger l'indentation d'un algorithme ecrit en pseudocode.
----
Menu
----
1. Indenter pseudocode
2. Quitter
Entrez votre choix : 1
invalid
Entrez votre choix : 2
invalid
Entrez votre choix : 3
invalid
Entrez votre choix :
I used the while loop but for any input the user chooses, the result is the same.