mercredi 7 octobre 2015

Is there a way of reducing the number of "if" statements I use?

For class I am creating a Binary to Denary converter and I can't seem to get it to work. My use of if and else if statements seems to make my code very cluttered.

Is there a way of reducing the amount of clutter? The task says that it would be useful to investigate: .toString, .substring(int a, int b) and java.lang.Math.pow(double a, double b). Anyway of also getting this to work? All the values, since they're defined as 0 to begin with, end up all being 0.

import java.util.Scanner;


public static void main(String[] args) {

Scanner userInput = new Scanner(System.in);    
    String binary;
    int value0 = 0;
    int value1 = 0;
    int value2 = 0;
    int value3 = 0;
    int value4 = 0;
    int value5 = 0;
    int value6 = 0;
    int value7 = 0;

    System.out.println("Welcome to the Binary to Denary converter!");
    System.out.println("Please enter an 8-BIT Binary value:");

    binary = userInput.next();
    char result0 = binary.charAt(0);
    char result1 = binary.charAt(1);
    char result2 = binary.charAt(2);
    char result3 = binary.charAt(3);
    char result4 = binary.charAt(4);
    char result5 = binary.charAt(5);
    char result6 = binary.charAt(6);
    char result7 = binary.charAt(7);

    if (result0 == 1){
    value0 = 128;
    }
    else if (result0 == 0){
    value0=0;
}      
    if (result1 == 1){
    value1 = 64;    
    }
    else if (result1 == 0){
    value1=0;    
}
    if (result2 == 1){
    value2 = 32;        
    }
    else if (result2 == 0){
    value2=0;
}
    if (result3 == 1){
    value3 = 16;        
    }
    else if (result3 == 0){
    value3=0;
} 
    if (result4 == 1){
    value4 = 8;        
    }
    else if (result4 == 0){
    value4=0;
}
    if (result5 == 1){
    value5 = 4;        
    }
    else if (result5 == 0){
    value5=0;
}
    if (result6 == 1){
    value6 = 2;        
    }
    else if (result6 == 0){
    value6=0;
}
    if (result7 == 1){
    value7 = 1;        
    }
    else if (result7 == 0){
    value7=0;   
}
    int answer = value0+value1+value2+value3+value4+value5+value6+value7;

    System.out.println("Your Denary value is:"+value0+"+"+value1+"+"+value2+"+"+value3+"+"+value4+"+"+value5+"+"+value6+"+"+value7+"="+answer);
}
}

Aucun commentaire:

Enregistrer un commentaire