Is there a command in java to make the program go back to the beginning of a loop

后端 未结 5 815
独厮守ぢ
独厮守ぢ 2021-01-22 12:22

I am trying to make a typing adventure kind of game in java, however i need a command at least similar to the one in the title, here is the code

import java.util         


        
5条回答
  •  迷失自我
    2021-01-22 12:31

    I had this same problem for my CS class: Here's what I did. First off, you NEED to use a loop. I used a 'while' loop.

    So say you are at a point in your dialogue where someone asks some one else (like the martial arts master asks the player) for something, and the answer choices are "y" or "n". But the player types in a "m". This would produce an error. To fix it, you need to make something (a loop) that will keep checking whether or not the user typed a valid response, and continue the program accordingly. Now the code...

    //Ask if they want to see the rules.    
    System.out.println("Welcome Player One");  
    System.out.println("Would you like to read the rules of the gem?");  
    System.out.println("[y]Yes, please / [n]I know the rules."); //So you made it clear that the choices are 'y' or 'n' (yes or no).
    
    //Decide if they hit yes or no.  
    char Response; //Variable to hold user response.  
    Scanner Console = new Scanner(System.in); //I don't know why, exactly, but you need this.  
    Response = Console.next().charAt(0); //Set response to the user input. A input field will appear.  
    while(true){  //Making the parameter 'true' makes the flow of the loop depend on the parameters in the if statements (I think).  
      if(Response == 'y' || Response == 'Y'){  
       System.out.println("Here are the rules:");  
       break; //break will make the flow exit the while loop (so you can continue adding the rest of your code).  
      }  
      else if(Response == 'n' || Response == 'N'){  
       System.out.println("Then let us continue:");  
       break;  
      }  
      else{  
       System.out.println("Would you like to read the rules of the gem?"  
       System.out.println("You have to enter (y)yes or (n)no...");  
       Response = Console.next().charAt(0); //Just like before, input field will  appear to give them the chance to change their response to a valid one.  
       continue; //This has to be 'continue' so that the loop will continue to "check" for the value that needs to be input by the user.  
      }  
    }
    

    Hope this helps, cheers.

提交回复
热议问题