I'm trying to create a binary to decimal converter. The program also includes a decimal to binary converter, but I'm trying to focus on the binary to decimal converter first. I get an error that says the string index is out of range.
My program includes one method so far to convert the binary to decimal.
here's the program if you want to take a look at it.
import java.util.Scanner; import java.lang.Math; public class NumberConverter { public static void main (String[] args) { Scanner scan = new Scanner(System.in); String binarynum; int choice; int i = 0; String binaryreversed = ""; int decimalnum = 0; System.out.println("This program will convert binary to decimal or decimal to binary."); System.out.println("Please enter a number for what you want to do:" + "\n 1. Convert Binary to Decimal." + "\n 2. Convert Decimal to Binary." + "\n 3. Exit the program."); choice = scan.nextInt(); while(choice != 3) { if(choice == 1)//converts binary to decimal { decimalnum = ConvertBinarytoDecimal(binaryreversed); System.out.println("Enter a Binary number such as \"0111010\". " +"\n The program will convert it to decimal."); binarynum = scan.nextLine(); while (i < binarynum.length()); { binaryreversed = binaryreversed + binarynum.charAt(i); i++; } } } } public static int ConvertBinarytoDecimal(String binaryreversed) { int decimalnum = 0; int i = 0; while ( i < binaryreversed.length()); { if(binaryreversed.charAt(i)== '1') { decimalnum = decimalnum + (int)Math.pow(2,i); i++; } else if(binaryreversed.charAt(i)== '0') i++; } return decimalnum; } }