0
x1 = input.nextLine();
    if(x1.length() == 2){
        if(x1.charAt(0) == 'a' || x1.charAt(0) == 'A'){
            if(x1.charAt(1) == '1'){
                if(a1 == 0){
                    a1 = 1;
                    px1 = "a1";
                }
            }

If a1 is not equal to 0, I want to be able to go back and ask the user to retry to enter a valid entry.. But there is a lot more code that follows (after the curly brackets)... So I don't want to have to recopy all that code because it will end up being copy/pasted about 20 times then I have to go and edit it all...

Thanks in advance for the help!

  • 3
    Use a while loop. Pseudocode: `While input is not equal do what I expect: Ask for new input, do processing` – Kon Jan 14 '16 at 17:53

2 Answers2

2

In short & precisely -

boolean doLoop=true;
do{
   x1 = input.nextLine();
   if(x1.length() == 2 && (x1.charAt(0) == 'a' || x1.charAt(0) == 'A') && x1.charAt(1) == '1'){
     a1 = 1;
     px1 = "a1";
     doLoop = false;
   }
}while(doLoop);
Subhrajyoti Majumder
  • 40,646
  • 13
  • 77
  • 103
0

The best way of implementing this is a do while loop :

// Define your variables
do {
  // input your variables
}while(NotValidContition);

I couldn't understand exactly your use case, but I want the user to input an integer for example, I would code this :

Integer x = null;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input;

do{
  System.out.println("Please input a number :");
  try{
    input = br.readLine();
    x = Integer.parse(input);
  }catch(IOException io){
    System.out.println("IO ERROR");
  }catch (NumberFormatException nfe){
    System.out.println("Error: Input was not a number !");
  }
}while (x != null);

UPDATE : As explained in here JAVA does have a goto keyword, but AFAIK it is not being used, and it was included in the keyword list so that any code with the keyword wouldn't compile in the present so that it wouldn't break in the future IF the feature gets added in a later release of JAVA.

Community
  • 1
  • 1
Younes Regaieg
  • 4,156
  • 2
  • 21
  • 37
  • the do while loops is not gonna work.. i didn't think i should have posted the entirety of my code, but there are loops to check if the input is a1, a2, a3, b1, b2, b3, c1, c2, or c3... so it's not possible to put a do while loop in there... I heard there might be a goto command where i can send it back to a different line of code – Austin Loach Jan 14 '16 at 18:04
  • I made an update to address the goto keyword in JAVA – Younes Regaieg Jan 14 '16 at 18:32