For some reason i'm loosing access to my variables inside the switch statement,
I am not allowed to use any global variables.
import java.util.Scanner;
public class Projet {
public static void main(String[] args) {
String clef="vide";
Scanner in = new Scanner(System.in);
showMenu(in);
in.close();
}
Main method is kept as clean as possible ... calling the menu just once.
public static void showMenu(Scanner in){
System.out.printf("******************************************%n" +
"* Choisissez une des options suivantes : *%n" +
"* 1) Saisir la clef secrète *%n" +
"* 2) Afficher la clef secrète *%n" +
"*******************************************%n%n%n");
choice(in);
}
showMenu(in)
Depending on the choice made we would get into a specific case.
public static int getNumber(Scanner in){
int choice = in.nextInt();
in.nextLine();
return choice;
}
getNumber(in)
returning our previous input so we can get into the case. Double function, will be removed in next version.
public static void choice(Scanner in){
try {
switch(getNumber(in)){
Case 1 ->
We are supose to keep the clef variable which is returned by saisirClef(in)
case 1:
String clef = saisirClef(in);
break;
Case 2 -> It should have kept the value from case 1 ?
case 2:
afficherClef();
break;
default:
System.out.println("Default");
break;
}
} catch (Exception e) {
System.out.println("Please enter a number");
//choice(in);
}
}
saisirClef(in)
method called in case one.
public static String saisirClef(Scanner in){
System.out.println("Saisir la clef secrète :");
String a = in.nextLine();
System.out.println("Voici ce que vous avez tapper : "+a);
return a;
}
afficherClef
method called in case 2
public static String afficherClef() {
return clef;
}
}
Every time showMenu(in)
my variables get cleared.
I should be able to transport the clef variable from case to case ...
Could you please help me figure out what am I doing wrong here ? I am using return statements, I just don't understand why they disappears.
I'm not sure what you are trying to achieve. There are multiple compilation and logical error in your code. I have tried to correct them as per my understanding and posting the code (since it is too large to post as comment) with comments where I made changes. Hope this helps you.