How do I make my program repeat according to certain circumstances?

后端 未结 3 1530
说谎
说谎 2020-12-04 03:46
import java.util.Scanner;

public class MyFirstGame {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        Syste         


        
相关标签:
3条回答
  • 2020-12-04 04:13

    just put your code inside the do-while loop

    Scanner scanner = new Scanner(System.in);
    
    do
    {
        System.out.println("Please Enter A Number: ");
        double s = scanner.nextDouble();
    
        double realerNumber = Math.round( Math.random() * 10 );
    
        System.out.println(realerNumber);
    
        if(s==realerNumber) {
            System.out.println("You Win!");
        } else {
            System.out.println("Try Again...");
        }
    }
    while(someCondition);
    

    the someCondition can be for example a counter (if you want to play n times just set counter to n and decrease it every loop iteration then check if it is 0 in while) or some function checking if a key is pressed (like escape)

    int n = 5;
    
    do
    {
        n--;
        ...
    }
    while(n > 0);
    
    0 讨论(0)
  • 2020-12-04 04:17

    This will run forever, but it's the idea mentioned in the first comment

        ...
        Scanner scanner = new Scanner(System.in);
        while(true){ // add this after Scanner ... declaration
           ...
            } // end of existing else block
        } // end of while loop, so add this single brace
        ...
    
    0 讨论(0)
  • 2020-12-04 04:23

    Use a while loop:

    long realerNumber = Math.round(realNumber);
    // first guess
    long guess = scanner.nextLong();
    while (guess != realerNumber) {
        System.out.println("Try Again...");
        // guess again
        guess = scanner.nextInt();
    }
    
    System.out.println("You Win!");
    

    There is already a class to generate random numbers, you could use it:

    // TODO: move to constant
    int MAX = 10;
    // nextInt(int n) generates a number in the range [0, n)
    int randomNumber = new Random().nextInt(MAX + 1)
    
    0 讨论(0)
提交回复
热议问题