Hello guys, i have assignment for converting binary numbers to decimal in java and i did write the code but want any feedback from you guys if i can make the code more efficient or if i did something that would reduce points from the assignment.
Code:import java.util.Scanner; public class ConvertBinary { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter a four, or more, digit binary number: "); String Binary = input.nextLine(); int decimal = convertToDecimal(Binary); System.out.println("The binary number you have chose equals this in decimal: "+ decimal); } private static int convertToDecimal(String binary) { final int base = 2; int decimal = 0; for (int i = 0; i < binary.length(); i++) { if (binary.charAt(i) == '0') { decimal += 0 * Math.pow(base, binary.length() - i - 1); } else if (binary.charAt(i) == '1') { decimal += 1 * Math.pow(base, binary.length() - i - 1); } else { System.out.println("Use the number one and/or zero please"); } } return decimal; } }
the example we were given was this:
Enter a four digit binary number (e.g. "0111")
> 0101
0101 converted to decimal is 5
**For the new page
Why are you multiplying by 0 (or doing anything for the "0" case)?
I'd probably write a recursive function.
to be honest i don't know how to do a recursive function i will look at up