gpt4 book ai didi

java - 如何在加法器游戏中检查第三个变量(ans)?

转载 作者:行者123 更新时间:2023-11-30 11:32:08 24 4
gpt4 key购买 nike

好吧,我整整 48 小时都在思考这个问题 :(

添加游戏假设给出 2 个随机数(将它们相加),跟踪正确回答所需的尝试次数,并根据最多 4 次的尝试次数给予分数,在 4 次尝试时数字重置为零点,它会告诉您答案,然后再生成 2 个数字。在任何时候,如果您的猜测包括 99,游戏就会结束。不使用 fordo while 包括 break;

如何让它在 ans == 99 时停止?

import java.util.Scanner;
import java.lang.Math;

public class AdderGame {
public static void main (String [] args){
int ans = 0;
int tries;
int score = 0;

Player one = new Player (0 , 0);
while (ans != 99) {
tries = one.getTry();
ans = one.getAns();

switch (tries) {
case 1: score += 5; break;
case 2: score +=3; break;
case 3: score += 1; break;
case 4: score += 0;
System.out.print("The right answer is "); break;
}
}
System.out.print("Your Score is " + score);
}
}


import java.lang.Math;
import java.util.Scanner;

public class Player {
int ran1, ran2;
int tries = 1;
int answer;
int guess;

public Player(int trys, int ans) {
tries = trys;
answer = ans;
}

public int getTry() m{
Scanner input = new Scanner(System.in);
ran1 = (int) (19 * Math.random());
ran2 = (int) (19 * Math.random());
answer = ran1 + ran2;

do {
System.out.print(ran1 + " + " + ran2 + ": ");
guess = input.nextInt();
if (guess == answer) {
return (tries);
} else {
tries += 1;
}
} while (tries <= 4 && answer != guess || guess != 99);
return (tries);
}

public int getAns() {
return (answer);
}
}

最佳答案

您的程序不正确有多种原因。

  1. 你正在使用“答案”来停止,而不是猜测。您应该检查以确保“猜测”不是 99。
  2. 在您的 Player while 循环 中,您需要更改该逻辑以使其在猜测为 99 时也停止。现在您正在使用逻辑 or但您需要将其更改为

修改后的代码:

public class AdderGame {
public static void main (String [] args){
int ans = 0;
int guess = 0;
int tries;
int score = 0;

Player one = new Player (0 , 0);
while (guess != 99) {
tries = one.getTry();
ans = one.getAns();
guess = one.getGuess(); // notice I'm getting the guess
switch (tries) {
case 1: score += 5; break;
case 2: score += 3; break;
case 3: score += 1; break;
case 4: score += 0;
System.out.print("The right answer is "); break;
}
}

System.out.print("Your Score is " + score);
}
}

// Methods from inside of your Player class
public int getTry(){
Scanner input = new Scanner(System.in);
ran1 = (int) (19 * Math.random());
ran2 = (int) (19 * Math.random());
answer = ran1 + ran2;

do {
System.out.print(ran1 + " + " + ran2 + ": ");
guess = input.nextInt();
if (guess == answer) {
return (tries);
} else {
tries += 1;
}
// Notice that it's now `&& guess != 99` instead of `||`
} while (tries <= 4 && answer != guess && guess != 99);
return (tries);
}
// new getter for getting the guess
public int getGuess(){
return guess;
}

关于java - 如何在加法器游戏中检查第三个变量(ans)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16841474/

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