2016-06-29 54 views
-1

我的代碼打印出將n轉換成基數b的結果。我在我的代碼中使用了%。如果兩個數的%給出了例如「11」的輸出,怎麼我分開的數字,所以我的輸出看起來像「1 + 1」在java中分隔數字

 String s; 
     int r; 

     if(n < b){ 
      return n + " "; 
     }else{ 
      s = converting(n/b,b); 
      r = (n % b); 
     } 
     return s + r; 
    } 

    public static void main(String[] args) { 
     Scanner scnr = new Scanner (System.in); 
     RecursionMethod num = new RecursionMethod(); 
     System.out.println("Enter Values: "); 
     System.out.print("B: "); 
     int first = scnr.nextInt(); 
     System.out.print("B: "); 
     int second = scnr.nextInt(); 
     System.out.println("Result: " + num.converting(first,second)); 
     scnr.close(); 
    } 
} 

回答

1

一種選擇是將其轉換爲一個字符串,然後使用字符串函數來做到這一點。

所以:

int result = num.converting(first,second); 
String strResults = String.valueOf(result); 
System.out.println("Result: " + strResults.substring(0,0) + " " + strResults.substring(1, 1)); 

取決於你希望你可能不得不做出比這要處理超過2個位數更一般的情況下,類型的結果。

也可能有一種與printf格式的方法,但我從來不喜歡printf格式。使用while循環

1

嘗試:

int num; // = the int you want to separate 

while (num > 0) { 
    print(num % 10); 
    num = num/10; 
} 
0

爲什麼不通過Integer.toString(int i, int radix),其中基數是隻爲基地看中字做基轉換,然後使用字符串操作大衛·芬德利建議(雖然我可能使用String#join和String#split),例如:

String converted = Integer.toString(n, b); 
String spaceSeparated = (String.join(" ", converted.split("")));