Ceri Westcott
Ceri Westcott

Reputation: 59

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);   
    }
}

Upvotes: 1

Views: 543

Answers (3)

janos
janos

Reputation: 124646

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

Upvotes: 1

brso05
brso05

Reputation: 13222

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.

Upvotes: 1

Vighanesh Gursale
Vighanesh Gursale

Reputation: 921

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);

   }
}

Upvotes: 2

Related Questions