gpt4 book ai didi

java - 在 Java 中,为什么我不能从超过 255 的十进制数中获取 9 个字符?是符号位吗?

转载 作者:行者123 更新时间:2023-11-30 05:56:39 26 4
gpt4 key购买 nike

这是针对头尾 Java 作业的,您可以在网上找到几个地方(例如 http://www.javaproblems.com/2013/01/medium-problem-tricky-heads-and-tails.html )

这个想法是输入一个十进制 0 到 511,并让它输出一个 3 x 3 的 H 或 T 矩阵,表示 0 或 1(我的工作范围是 0 到 255)

这是我的尝试,但我无法工作:

public static void main(String[] args) {

@SuppressWarnings("resource")
Scanner keyboard = new Scanner(System.in);
//System.out.println("Please enter a number between 0 and 511: ");
//int num = keyboard.nextInt();
int num = 458;
String binNum = "";
int temp;
String[][] coinArr = new String[3][3]; // = [][];

while(num > 0)
{
temp = (int) (num % 2);
binNum = binNum + "" + temp;
num = (int) (num / 2);
}

System.out.println("binNum length is " + binNum.length());
System.out.println("binNum is " + binNum);

binNum = String.format((binNum.length() < 9 ? ("%0"+ (9 - binNum.length())+"d%s") : "%0$d%s"), 0 ,binNum);
System.out.println("binNum length is " + binNum.length());
System.out.println("binNum is " + binNum);

int k=0;
for(int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
binNum = binNum.replaceAll("0", "H");
binNum = binNum.replaceAll("1", "T");
coinArr[i][j] = binNum.substring(k, k+1);
k++;
System.out.print(coinArr[i][j]);
}
System.out.println();
}
}

最佳答案

您从十进制到二进制的转换是错误的,正确的是:

while(num > 0)
{
temp = (int) (num % 2);
binNum = temp + "" + binNum;
num = (int) (num / 2);
}

那么你的 binNum 中只需要 9 个字符:

binNum = binNum.length() < 9 ? String.format("%0"+ (9 - binNum.length())+"d%s", 0 ,binNum) : binNum;

// You don't need this inside your loop
binNum = binNum.replaceAll("0", "H");
binNum = binNum.replaceAll("1", "T");

int k=0;
for(int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
coinArr[i][j] = String.valueOf(binNum.charAt(k));
k++;
System.out.print(coinArr[i][j]);
}
System.out.println();
}

关于java - 在 Java 中,为什么我不能从超过 255 的十进制数中获取 9 个字符?是符号位吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53057247/

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