I am having an issue with this program, I keep getting the number 15 everytime I type in a code. There is also the instructions for the module itself. //PSEUDOCODE //Write a program that prompts the user for a binary number //(from 3 to 8 bits) as a String and converts it to base-10 decimal value //There are several ways to do this in Java but your program must use a for loop and first principles to perform the conversion //Print the base-10 number when the loop ends public static void main(String args[]) { long sum = 0; System.out.println("Enter a binary number: "); Scanner scan = new Scanner(System.in); String s = scan.next(); long result = 0; for (int i = 0; i < s.length(); i++) { result = (long) (result + (s.charAt(1) - '0') * Math.pow(2, s.length()- i - 1)); scan.close(); } System.out.println(result); } }
I am having an issue with this program, I keep getting the number 15 everytime I type in a code. There is also the instructions for the module itself.
//PSEUDOCODE
//Write a program that prompts the user for a binary number
//(from 3 to 8 bits) as a String and converts it to base-10 decimal value
//There are several ways to do this in Java but your program must use a for loop and first principles to perform the conversion
//Print the base-10 number when the loop ends
public static void main(String args[]) {
long sum = 0;
System.out.println("Enter a binary number: ");
Scanner scan = new Scanner(System.in);
String s = scan.next();
long result = 0;
for (int i = 0; i < s.length(); i++) {
result = (long) (result + (s.charAt(1) - '0') * Math.pow(2, s.length()- i - 1));
scan.close();
}
System.out.println(result);
}
}
Trending now
This is a popular solution!
Step by step
Solved in 3 steps with 2 images