2016-09-12 35 views
-4

我正在解決TopCoder中的問題,我需要編寫一個必須返回String[]的方法。這是我的方法,它沒有任何錯誤的工作:在沒有逗號的java方法中返回String []數組

public static String[] decode(String encoded) 
{ 
    char[] test = encoded.toCharArray(); 
    int[] decode_arr = new int[test.length]; 
    String[] result = new String[2]; 
    boolean flag= false; 
    for(int i=0;i<2;i++) 
    { 
     flag = false; 
     decode_arr[0] = i; 
     decode_arr[1] = Character.getNumericValue(test[0])-decode_arr[0]; 

     for(int x=2;x<test.length;x++) 
     { 
      decode_arr[x] = Character.getNumericValue(test[x-1]) - decode_arr[x-2]-decode_arr[x-1]; 
      if(decode_arr[x]>1 || decode_arr[x]<0) 
       flag=true; 
     } 
     if(!flag) 
      result[i] = Arrays.toString(decode_arr); 
     else 
      result[i] = "NONE"; 

     //System.out.println(Arrays.toString(decode_arr)); 
     decode_arr = null; 
     decode_arr = new int[test.length]; 
    } 

    return result; 

} 

現在的問題是編譯器期望的值,而不逗號,例如,如果輸出是:

"01101001101101001101001001001101001", "10110010110110010110010010010110010"

我得到的是什麼是:

[0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0 , 0, 1, 1, 0, 1, 0, 0, 1] [1, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 0 , 1, 0, 1, 1, 0, 0, 1, 0]

我失去了任何共同調整或我應該修剪輸出nd提交它的方式應該是?請幫助!

+3

我的猜測是'Arrays.toString(decode_arr);'不是正確的選擇。我建議建立一個預期字符的字符[]並將其轉換爲字符串' –

+0

輸出總是爲0還是1? – SMA

回答

0

這就是Arrays.toString()所做的。顯示的值組與List清晰地相同。在以下情況下:

int[] array = {11, 2}; // printed as "112" afterwards 

..你不能清楚地看到,如果它的[11, 2],或[1, 12]或僅[112]陣列。

但是如果你渴望那種輸出,嘗試更換一個空字符的所有不想要的字符:

String out = Arrays.toString(array).replace(", ", "").replace("[", "").replace("]", ""); 

在具有[]字符作爲一些值的情況下,我建議你最好這樣安全的方式:

String arrayAsString = Arrays.toString(array); 
String out = arrayAsString.substring(1,arrayAsString.length()-1).replace(", ","");