简体   繁体   中英

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.

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. 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:

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.

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:

  • Use more meaningful names
  • Declare variables right before you use them. Especially good to initialize at the same time
  • Use a builder to build the binary string efficiently

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM