[英]Concatenating two int in a loop?
I've got a Decimal to binary converter but can't concatenate the bitNum
and holder
as they just simple add to each other. 我有一个十进制到二进制的转换器,但是不能将
bitNum
和holder
串联在一起,因为它们只是简单地相互加法。
I know I can parse it but would I have to parse it every time it loops? 我知道我可以解析它,但是每次循环时我都必须解析吗?
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);
}
}
I come to know the reason. 我知道原因。 As user want to concatenate the string you can use concat() method provided by Java.
当用户想要连接字符串时,可以使用Java提供的concat()方法。 While finding the binary no we should reverse the string while printing and you must know the reason why we reverse the string.
找到二进制文件时,我们应该在打印时反转字符串,并且您必须知道反转字符串的原因。 them Use the following code:
他们使用以下代码:
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);
}
}
Make bitNum a string and do: 将bitNum设置为字符串,然后执行以下操作:
binNum = holder + binNum;
You can't concatenate ints (you can add) but you can concatenate Strings. 您不能串联整数(可以添加),但是可以串联字符串。 The int will automatically be converted to a String when you concatenate it with a String.
将int与String串联时,它将自动将其转换为String。
A better implementation: 更好的实现:
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);
Improvements: 改进之处:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.