-1

i'm trying to convert decimal to binary without any arrays or without recursion. I'm aware of the one command that you can use to convert decimal to binary but i'm trying to do this manually. Any help would be appreciated.

   public class Decimaltobinary {

    public static String decimalToBinary(int valueIn){

        //    String binaryOut = "";
        //    int counter = 0;
        int remainder, i = 0;

        while (valueIn != 0){
            remainder = valueIn % 2;
            valueIn /= 2;
            int binaryNum += remainder * i;
            i *= 10;
        }
        return binaryNum;

    }

    /**
    * @param args the command line arguments
    */

    public static void main(String[] args) {
        // TODO code application logic here
        Scanner keyboard = new Scanner (System.in);
        System.out.println("Please enter the decimal number: ");
        int valueIn = keyboard.nextInt ();
        String outputOut = decimalToBinary(valueIn);
        System.out.println ("The output is: " +outputOut);    
    }

}

I'm getting an error for the return BinaryNum statement that says 'cannot find symbol' and an error for the

 int binaryNum += remainder * i;

statement. The error says '; expected'.

The Head Rush
  • 3,157
  • 2
  • 25
  • 45
Liz Mcguire
  • 1
  • 1
  • 5
  • 1
    You know about `Integer.toBinaryString()` right? Just checking to make sure you're re-implementing it on purpose. – markspace Nov 05 '18 at 18:54
  • So this method has real problems. Your method returns a string but you are trying to return in integer. Can't do that. Please fix the obvious syntax errors in your code first. – markspace Nov 05 '18 at 18:56
  • @markspace i do know about it yes. i don't want to use that function but rather, make one of my own. – Liz Mcguire Nov 05 '18 at 18:59

1 Answers1

1

you declared binaryNum inside while loop so the scope of this variable will be inside the loop only, declare it outside the while loop and change binaryNum type to String

public class Decimaltobinary {

public static String decimalToBinary(int valueIn){

     //    String binaryOut = "";
     //    int counter = 0;
      int remainder, i = 0;
       String binaryNum ="";
      while (valueIn != 0){
        remainder = valueIn % 2;
        valueIn /= 2;
        binaryNum = remainder+binaryNum;
      }
     return binaryNum;
}

/**
* @param args the command line arguments
*/

public static void main(String[] args) {
    // TODO code application logic here
    Scanner keyboard = new Scanner (System.in);
    System.out.println("Please enter the decimal number: ");
    int valueIn = keyboard.nextInt ();
    String outputOut = decimalToBinary(valueIn);
    System.out.println ("The output is: " +outputOut);    
   }

}
Ryuzaki L
  • 37,302
  • 12
  • 68
  • 98