[英]Concatenating two int in a loop?
我有一個十進制到二進制的轉換器,但是不能將bitNum
和holder
串聯在一起,因為它們只是簡單地相互加法。
我知道我可以解析它,但是每次循環時我都必須解析嗎?
public class DecToBin {
public static void main(String[] args){
int no1;
int binNum = 0;
Scanner s = new Scanner(System.in);
no1 = s.nextInt();
while(no1 > 0){
int holder = no1 % 2;
System.out.println(holder);
binNum = holder + binNum;
no1 /= 2;
}
System.out.println("Your number is binary is: " + binNum);
}
}
我知道原因。 當用戶想要連接字符串時,可以使用Java提供的concat()方法。 找到二進制文件時,我們應該在打印時反轉字符串,並且您必須知道反轉字符串的原因。 他們使用以下代碼:
import java.util.*;
public class DecToBin {
public static void main(String[] args){
int no1;
Scanner s = new Scanner(System.in);
no1 = s.nextInt();
String binNum = "";
while(no1 > 0){
int holder = no1 % 2;
System.out.println(holder);
binNum.concat(Integer.toString(holder));
no1 /= 2;
}
String actual = new StringBuilder(binNum).reverse().toString();
System.out.println("Your number is binary is: " + actual);
}
}
將bitNum設置為字符串,然后執行以下操作:
binNum = holder + binNum;
您不能串聯整數(可以添加),但是可以串聯字符串。 將int與String串聯時,它將自動將其轉換為String。
更好的實現:
Scanner scanner = new Scanner(System.in);
int num = scanner.nextInt();
StringBuilder builder = new StringBuilder();
while (num > 0) {
builder.append(num % 2);
num /= 2;
}
String actual = builder.reverse().toString();
System.out.println("Your number is binary is: " + actual);
改進之處:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.