vendredi 11 janvier 2019

strange problem with else (program jump to else if there is no reason to do that)

So im practicing java writing simple programs. I made one to change binary numbers to decimal. In last loop below all if(){}'s my program jumps to else without reason to do so. Ive changed this last else to another if statement and program is running properly. But i wonder HOW it is possible that first program is jumping to else. What property of if-else statements is making that? Im puting code and outputs of both programs below:

import java.util.Scanner;
public class NumberToBinary1 {
public static void main(String[] args) {
    System.out.println("Put binary number: ");
    Scanner sn = new Scanner(System.in);
    String container = sn.nextLine();
    System.out.println(binaryToNumber(container));



private static double binaryToNumber(String container) {
    int numberLength = container.length();
    double result = 0;
    double power = 0;

    for (int i = numberLength-1; i >= 0; i--) {
        char a = container.charAt(i);
        int x =a;
        if (x == 49) {                          //if digit from binary number is 1 add 2^(number of power) to result
            result += java.lang.Math.pow(2d, power);
            power++;
        }
        if (x==48) {                            //if digit from binary number is 0, just skip to next power of 2
            power++;
        }
        else {
            System.out.println("issue with "+(i+1)+ " number"); //else give error with i+1th digit
        }
    } return result;
}

}

Put binary number: 
10110105
issue with 8 digit
issue with 6 digit
issue with 4 digit
issue with 3 digit
issue with 1 digit
90.0

#### AND SECOND:
import java.util.Scanner;

public class NumberToBinary2 {
public static void main(String[] args) {
    System.out.println("Put binary number: ");
    Scanner sn = new Scanner(System.in);
    String container = sn.nextLine();
    System.out.println(binaryToNumber(container));
}


private static double binaryToNumber(String container) {
    int numberLength = container.length();
    double result = 0;
    double power = 0;

    for (int i = numberLength-1; i >= 0; i--) {
        char a = container.charAt(i);
        int x =a;
        if (x == 49) {                                  //if digit from binary number is 1 add 2^(number of power) to result
            result += java.lang.Math.pow(2d, power);
            power++;
        }
        if (x==48){                                     //if digit from binary number is 0, just skip to next power of 2
            power++;
        }
        if(x!=49 && x!=48) {System.out.println("issue with "+(i+1)+" digit"); //if digit from binary number is not 1 or 0 -> give error
        }
    }return result;
}

}

Put binary number: 
10110105
issue with 8 digit
90.0

Aucun commentaire:

Enregistrer un commentaire