jeudi 4 mars 2021

if statement, not equaling value i entered

This is a assignment where i have to convert binary to decimal

Im having trouble seeing why, when i put num == 0 in the if statement, it doesnt accept it as true, even though num has a value of 0/1. The only way i have found to make the statement true is by doing num == 49 or 48.

The System.out.print was not initially part of the code, but was using it to see the values of num and val. From what im seeing num does have the value of 1/0 but when i did the val = num, val suddenly changes to 49 for 1 or 48 for 0.

why is this and how can i fix it thank you

import java.util.Scanner;

public class Converter{
    public static void main(String [] args){
        Scanner in = new Scanner(System.in);
        String str = "";
        boolean ifBinary = false;
        
        System.out.println("Enter a binary string");
        str = in.next();
        
        ifBinary = isBinary(str);
        
        if(ifBinary == true){
            //BinaryToDecimal(str);
        }
        else if (ifBinary == false){
            System.out.println("The binary string entered is not valid");
        }
    }
    
    public static boolean isBinary(String str){
        //int strNum = Integer.parseInt(str);
        int strLen = str.length();
        int binary = 0;
        boolean isBinary = false;
        char num;
        
        for(int i = 0; i < strLen; i++){
            num = str.charAt(i);
            
            int val = num ;
            System.out.println(num + " " + val);

            if(num == 49){
                binary++;
            }
            else if(num == 48 ){
                binary++;
            }
            else{
                isBinary = false;
            }
        }
        
        if(binary == strLen){
            isBinary = true;
        }
        
        return isBinary;
    }
    
    
  }


Aucun commentaire:

Enregistrer un commentaire