'Why is my java code here behaving this way where it returns true while it should return false? why if I remove the bool expression it still not work?
enter image description hereI included th image with the problem I have to solve; I thought it should be easy. And expected my code to work. Yet it didn't... I don't car a a lot about a solution as much as knowing what I did wrong
I know I need to start from right to left in reading the simple binary number(no encoding and not including negative values) as the power of 2 increases...but in this program it reads the binary number from left to right (like as a string)
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner myScanner = new Scanner(System.in);
System.out.println("Enter a 5-digit integer made of 0s and 1s:");
String binaryNumber = myScanner.nextLine();
int length = binaryNumber.length();
int index = 0;
int powerOfTwo =1 ;// 2^0
int decimalNumber = 0 ;
int currentChar = 0;
boolean isValid = true;
while(index < length && isValid) {
currentChar = binaryNumber.charAt(index);
if(currentChar > 1 /*Therefore not a 0 or 1*/) {
isValid = false;
System.out.println("Error at index "+index+" which is "+binaryNumber.charAt(index));
}
decimalNumber += (binaryNumber.charAt(index) * powerOfTwo) ;
powerOfTwo*=2;
index++;
}
if(isValid) {
System.out.println(binaryNumber+" in decimal is "+decimalNumber);
}else {
System.out.println(binaryNumber+" is not valid ");
}
}
}
I tried removing where th script checks if a character is a (0 or 1) or not. if (currentChar > 1 /*Therefore not a 0 or 1*/){....
Then it started calculating binary numbers like 0000 to be more than 0.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
