0

Here's my code:

import java.util.*;
public class binary{

public static void main(String args[])
{
    //input thing
    Scanner read = new Scanner(System.in);
    //variables
    String result = "";
    int input;
    //input
    input =read.nextInt();
    toBinary(input,result);
    System.out.println("Your binary is" + result);

}
public static String toBinary(int a,String b){
    StringBuilder sb = new StringBuilder();
    int y;
    int z=2;
    while(a >= 1){
        y = a%2;
        a/=z;
        sb.append(y);

    }
    b = sb.toString();
    invert(b);
    return b;
}
 public static String invert(String s) {
        String temp = "";
        for (int i = s.length() - 1; i >= 0; i--)
            temp += s.charAt(i);
        return temp;
    }
}

Can you help me on whats wrong, cause the return is blank. When I type in a number it comes out as nothing execpt "Your binary is".

Bobulous
  • 12,967
  • 4
  • 37
  • 68

1 Answers1

0

Your main problem is that you're not storing the returned values of your methods. toBinary(input,result); returns the result of the conversion but you're not storing it to any variable. Write result = toBinary(input,result); to fix that.

The same applies to your invert call. Write b = invert(b); to save the inverted value of b. Or write return invert(b); to return it immediately.

And just to make it sure: The line b = sb.toString(); won't change anything the variable result that was passed as the method argument. You're writing a new object reference to the variable. The old object remains unchanged in the memory. Also the variable result still references to the old object.

Tom
  • 16,842
  • 17
  • 45
  • 54
  • What exactly is a new object reference to the variable. I only did java for 10 days... – DarkWyvren Oct 05 '14 at 01:13
  • @DarkWyvren See these links for more information about objects and references to them: http://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value - http://docs.oracle.com/javase/tutorial/java/javaOO/usingobject.html - http://www.c4learn.com/java/java-assigning-object-reference/ - http://www.kdgregory.com/?page=java.refobj – Tom Oct 05 '14 at 08:39