gpt4 book ai didi

java - 检测整数何时仅由相同的数字组成

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

我正在编写一个可以玩游戏的 Java 程序。基本上你选择的是no。玩家和回合数,然后程序会按照以下规则向您显示每个玩家应该说的话:

- 假设玩家站成一圈,他们开始顺时针一一计数,直到有人达到仅由相同数字组成的数字(大于 10)。例如 11、22、33、..、444 等,然后它们开始逆时针计数

例如:P9:9; P10:10; P11:11; P12:13; P11:14 等(P10 = 玩家 10)

-当得到一个7的倍数、包含7或数字之和为7的数字时,他们说“Boltz”

例如:P1:13; P2:Boltz(而不是 14); P3:15; P4 博尔茨 (16); P5:博尔兹(17); P6:18等

我有Java代码,但我似乎无法在仅由一位数字组成的数字上从顺时针旋转到逆时针旋转

您能帮我解决 SameDigits 函数吗?谢谢!

import java.util.Scanner;

public class Boltz {
private static Scanner keyboard;

public static void main(String[] args) {
keyboard = new Scanner(System.in);

int nPlayers = 0;
int nRounds = 0;
int currentPlayer = 0;
int sum = 0;
int x = 0;
boolean isSameDigit = true;

System.out.print("Cati jucatori sunt? ");
nPlayers = keyboard.nextInt();

System.out.print("Cate runde sunt? ");
nRounds = keyboard.nextInt();

System.out.print("Jucatori: " + nPlayers + "; Runde: " + nRounds + "\n");

for (x = 1; x <= nPlayers * nRounds; x++) {

isSameDigit = SameDigits(currentPlayer);

if (currentPlayer < nPlayers && isSameDigit == false) {
currentPlayer++;
} else {
currentPlayer = 1;
}

if (currentPlayer > 1 && isSameDigit == true) {
currentPlayer--;
} else {
currentPlayer = nPlayers;
}

sum = digitSum(x);

if (x % 7 == 0 || String.valueOf(x).contains("7") || sum == 7) {
System.out.println("P:" + currentPlayer + " Boltz");
} else {
System.out.println("P:" + currentPlayer + " " + x);
}
}
}

public static int digitSum(int num) {
int suma = 0;
while (num > 0) {
suma = suma + num % 10;
num = num / 10;
}
return suma;
}

public static boolean SameDigits(int num) {
int add = 0, add2 = 0;

while (num > 0) {
add = add + num % 10;
add2 = add2 + add % 10;
num = num / 10;
}
if (add == add2) {
return true;
} else {
return false;
}

}

}

最佳答案

如果我理解正确的话,如果数字全部相同,您希望 SameDigits 返回 true,否则返回 false。单位数字也应该返回 true。这应该可以做到:

public static boolean SameDigits(int num) {
if (num < 0) return false; // or something else?

int onesDigit = num % 10;
num /= 10;
while (num > 0) {
if (onesDigit != num % 10) return false; // fail if digits differ
num /= 10;
}
return true;
}

附注您应该遵守 Java 命名约定并以小写字母开头(sameDigits 而不是 SameDigits)命名您的方法。

关于java - 检测整数何时仅由相同的数字组成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41657240/

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