gpt4 book ai didi

java - 我该如何添加 "You got it right in ... guesses!"

转载 作者:行者123 更新时间:2023-12-01 12:25:33 24 4
gpt4 key购买 nike

我需要添加“你猜对了……猜对了!”但我不太确定怎么做。有人可以向我解释一下如何在java中做到这一点吗?

我希望它在最后显示一个 println ,说明用户尝试了多少次才能获得正确的数字。

import java.util.*;

public class prog210c
{
public static void main()
{
Scanner sc = new Scanner(System.in);
Random rn = new Random();

int randomNum = rn.nextInt(90) + 10;

System.out.println("I am thinking of a number between 1 and 100");

while (true) {
System.out.print("What do you think it is? ");
int guess = sc.nextInt();

if(guess < randomNum)
{
System.out.println("Higher--Try Again");
}

else if(guess > randomNum)
{
System.out.println("Lower--Try Again");
}

else if(guess == randomNum)
{
System.out.println("Correct!");
break;
}

else
{
System.out.println("Enter a number between 1 and 100");
}
}

//System.out.println("You got it right in " + + " guesses");

} //end main
} //end class

最佳答案

只需创建一些 int 变量来存储您的尝试次数,并在每次读取猜测时递增它。

int attempts = 0;

System.out.println("I am thinking of a number between 1 and 100");

while (true) {
System.out.print("What do you think it is? ");
int guess = sc.nextInt();
attempts++;

/**
* The rest of your loop code here.
*/
}

System.out.println("You got it right in " + attempts + " guesses");

关于java - 我该如何添加 "You got it right in ... guesses!",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26372139/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com