binary to decimal converter
I need help with a basic program, I'm trying to convert a binary number, to a decimal, EX: 101 would become 5, this is my program so far, can anyone help me with it?
For some reason, it asks me for a number twice, and an error.
x is the index reading, because the first digit is 2^0, and the second is 2^1, i use x as the exponent, and the index number, and hasNextInt is the test, so when it runs out of numbers, the test comes back false, and the loop ends.
public class BinaryCounter
public static void main (String  args )
System.out.println ("Enter a number in base 2 format.");
Scanner kb = new Scanner(System.in);
String d = kb.nextLine ();
System.out.println ("You entered " + d);
x = 0;
decimal = 0;
int y = d.charAt(x);
int z = y^x;
x = x+1;
int almost = z + decimal;
int total = decimal + almost;
This is the error I get:
java.lang.StringIndexOutOfBoundsException: String index out of range: 3
at java.lang.String.charAt(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Nativ e Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknow n Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Un known Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at edu.rice.cs.drjava.model.compiler.JavacCompiler.ru nCommand(JavacCompiler.java:271)
Re: binary to decimal converter
That's because your program asks for different inputs. kb.nextLine() will read a line of input and returns it as a string. kb.nextInt() will read some more input and return it as an int.
For some reason, it asks me for a number twice,
You are wanting to work with (and convert) the string returned by nextLine(), so the nextInt() calls are probably not a good idea.
^ does not mean "exponentiation" in Java. In fact there is no exponentiation operator. There is Math.pow, but don't go rushing there yet. Make sure you have an algorithm or "recipe" that describes precisely what you are going to do. And check it with pencil and paper to make sure it really does what you want.
Consider a binary numeral like 10011. The first one represents 2 to the power 4. In other words the digits go from "big" to "little".