2016-12-03 75 views
0

我必須從一個範圍內取整數的用戶輸入,將其轉換爲二進制,並用二進制填充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

你要記住,這將不會再打印前導0的二進制如果沒有必要:例如:號碼2會是:10 ,因爲不需要使用多於2位。輸入號碼255並重新發布我所得到的結果。 – someRandomSerbianGuy

+0

@ Slay29我的結果是0 1 1在所有3行 –

+0

嘗試使用long來代替normal int。有什麼區別嗎? – someRandomSerbianGuy

回答

0

我認爲這將提供您可能真正想要的輸出。

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(); 
    } 


} 

}