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

时光总嘲笑我的痴心妄想 提交于 2019-11-28 14:30:51

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)

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);

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
    ...
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!