0
  • 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.

Laurel
  • 5,965
  • 14
  • 31
  • 57
  • Does this answer your question? [How do I compare strings in Java?](https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – Progman Nov 16 '22 at 14:16

1 Answers1

0

Because you're dealing with strings, you have to use .equals() as == compares the 2 strings as separate objects and will always return false (unless 2 strings are referring to the same object in memory).

if ( choixMenu.equals("1") || choixMenu.equals("2")){
//code
}

You could also go with parsing the input number as an integer and keep the ==.

int choixMenu;

//...

choixMenu = myObj.nextInt();
if ( choixMenu == 1 || choixMenu == 2) {
//code
}
Trooper Z
  • 1,617
  • 14
  • 31