Java Program. Eclipse IDE most recent. java 17.0.1.
program should prompt user a string representing a binary number. word must be 8 digits or less and must contain only 1s and 0s. If word is not 8 digits or less program should prompt user to make it such. If input does not contain only 1s and 0s, program should prompt user to only include 1s and 0s. I will post code that i have so far, i know that it is incomplete but im pretty much frozen where im at not sure where to go with it.
public static void main(String[] args) {
boolean isValid=false;
String bin = "";
int power =0;
int x=0;
long decimal = 0;
int answer=0;
Scanner sc = new Scanner(System.in);//create input method
do {
System.out.println("Please enter a binary number: ");//prompt user for binary number
bin = sc.nextLine();//bin equals input
if(bin.length()<=8) {//if length is 8 or less digits
for(int i =bin.length()-1; i>=0; i--) {//for the char at index i
if(((bin.charAt(i)=='1'))||(bin.charAt(i)=='0')){
isValid=true;
x=bin.indexOf(i);
power++;//power increase by 1 for each digit
decimal=(long)Math.pow(2,power);
System.out.println("The binary number you entered converted to decimal is: " + decimal);
break;
}else
isValid=false;
System.out.println("Invalid number. Please enter binary number containing only 1s and 0s:");
}
}else
System.out.println("Invalid number. Please enter binary number with 8 or less digits: ");
}
while(isValid=true);
}
}
output i get is:
Please enter a binary number:
0101
The binary number you entered converted to decimal is: 1
Please enter a binary number:
1111
The binary number you entered converted to decimal is: 2
Please enter a binary number:
1111111
The binary number you entered converted to decimal is: 4
Please enter a binary number:
111
The binary number you entered converted to decimal is: 8
Please enter a binary number:
11
The binary number you entered converted to decimal is: 16
Please enter a binary number:
01
The binary number you entered converted to decimal is: 32
Please enter a binary number: