我必须从一个范围中获取整数的用户输入,将其转换为二进制,并用二进制填充3x3数组。唯一的问题是,我的代码给我的输出只依赖于该二进制的前3个数字(即所有行的010001101 = 010)。
import java.util.Scanner;
public class HW11P02 {
public static void main(String[] args) {
Scanner in = new Scanner (System.in);
System.out.print("Enter a number between 0 and 511: ");
int n = in.nextInt();
String binary = Integer.toBinaryString(n);
binary = binary.format("%09d", Integer.parseInt(binary));
System.out.println(binary);
listArray(binary);
};
public static String[][] listArray(String binary) {
String[][] array = new String[3][3];
char ch = ' ';
String value = "";
for (int i = 0; i < 3; i++) {
for (int n = 0; n < 3; n++) {
ch = binary.charAt(n);
value = Character.toString(ch);
array[i][n] = value;
System.out.print(array[i][n] + " ");
}
System.out.println();
}
return array;
}
};
答案 0 :(得分:1)
我认为这将提供您可能真正想要的输出。
import java.util.Scanner;
公共类HW11P02 {
public static void main(String[] args)
{
Scanner in = new Scanner (System.in);
System.out.print("Enter a number between 0 and 511: ");
int n = in.nextInt();
String binary = Integer.toBinaryString(n);
binary = binary.format("%09d", Integer.parseInt(binary));
System.out.println(binary);
int result[][]=new int[3][3];
int position=0;
for (int i = 0; i < result.length; i++)
{
for (int j = 0; j < result.length; j++)
{
result[i][j]=binary.charAt(position++)-'0';
System.out.print(result[i][j]+" ");
}
System.out.println();
}
}
}