Results 1 to 2 of 2
Thread: binary to decimal converter
- 11-17-2011, 08:01 AM #1Member
- Join Date
- Nov 2011
- Rep Power
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)
- 11-17-2011, 08:47 AM #2Moderator
- Join Date
- Feb 2009
- New Zealand
- Rep Power
Re: binary to decimal converterFor 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".
- By ReDDs3D in forum New To JavaReplies: 0Last Post: 11-05-2011, 07:16 AM
- By HandMeTheBacon in forum New To JavaReplies: 0Last Post: 09-13-2011, 03:35 AM
- By irnie1994 in forum JCreatorReplies: 5Last Post: 08-25-2011, 07:32 PM
- By matejm1994 in forum New To JavaReplies: 3Last Post: 12-26-2010, 10:59 AM
- By c_walker in forum New To JavaReplies: 15Last Post: 11-24-2009, 03:38 PM