java中do until_在java中,如何在多次滿足條件之前運行while循環?

I am trying to make a program where the user can input the target as well as the amount of times he wants to hit the target. The problem is that I dont know how to make the while loop run more than once (satisfy the condition more than one time).

我正在嘗試創建一個程序,用戶可以輸入目標以及他想要達到目標的次數。問題是我不知道如何使while循環運行多次(滿足條件不止一次)。

Scanner target = new Scanner(System.in);

System.out.println("Enter dice target (1-10):");

int targetNumber = target.nextInt();

Scanner required = new Scanner(System.in);

System.out.println("Enter the number of required matches: ");

int requiredMatches = target.nextInt();

int number = (int) (1 + 10 * Math.random());

int sum = 1;

if (targetNumber > 10) {

System.out.println("Error");

}

else {

while (number != targetNumber) {

System.out.println("Your number is " + number);

number = (int) (1 + 10 * Math.random());

++sum;

}

System.out.println("You reached your target " + requiredMatches + " times in " + sum + " tries.");

}

The code lets me match the target only once, but I want it to be able to obtain the target value [RequiredMatches] times before it stops.

代碼只允許我匹配目標一次,但我希望它能夠在停止之前獲得目標值[RequiredMatches]次。

1 个解决方案

#1

2

If the number matches, then reduce the tries by 1.

如果數字匹配,則將嘗試減少1。

Scanner Required = new Scanner(System.in);

System.out.println("Enter the number of required matches: ");

int RequiredMatches = Target.nextInt();

int Number = (int) (1 + 10 * Math.random());

int sum = 1;

if (NumberTarget > 10) {

System.out.println("Error");

} else {

while ((Number != NumberTarget) || (RequiredMatches > 0)) {

System.out.println("Your number is " + Number);

Number = (int) (1 + 10 * Math.random());

++sum;

if (Number==NumberTarget) {

RequiredMatches--;

}

System.out.println("You reached your target " + RequiredMatches + " times in " + sum + " tries.");

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值