J.b. Daniel J.b. Daniel - 2 months ago 7
Java Question

Validation loop needed and Binary to Decimal not outputting the right answer

I know this is ugly, but it works (not really) it just compiles successfully

I cannot use Integer.parseInt() or Math.max

i have to define each char and set up the algorithm to check

I understand the concept of an 8 digit binary number like 11111111 has a decimal of 255 however in my program it is like 12495...WHAT GIVES what am i doing wrong?

also not every binary number is 8 characters, how can i allow the code to accept that and validate that only 1's and 0's are inputted in the prompt?

import java.util.Scanner;

public class Binary
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter Binary Number Please:");
String aString = keyboard.next();
char aChar = aString.charAt(0);
int digit_1 = aString.charAt(0);
char bChar = aString.charAt(1);
int digit_2 = aString.charAt(1);
char cChar = aString.charAt(2);
int digit_3 = aString.charAt(2);
char dChar = aString.charAt(3);
int digit_4 = aString.charAt(3);
char eChar = aString.charAt(4);
int digit_5 = aString.charAt(4);
char fChar = aString.charAt(5);
int digit_6 = aString.charAt(5);
char gChar = aString.charAt(6);
int digit_7 = aString.charAt(6);
char hChar = aString.charAt(7);
int digit_8 = aString.charAt(7);
float dec_1 = (digit_1*128);
float dec_2 = (digit_2*64);
float dec_3 = (digit_3*32);
float dec_4 = (digit_4*16);
float dec_5 = (digit_5*8);
float dec_6 = (digit_6*4);
float dec_7 = (digit_7*2);
float dec_8 = (digit_8*1);
float Answer = (dec_1+dec_2+dec_3+dec_4+dec_5+dec_6+dec_7+dec_8);
System.out.println(Answer);
}//End bracket method main
}//End bracket class Binary

Answer

Here ya go... should work - make sure you understand the code: Took all of 5 minutes...

import java.util.Scanner;

public class binary {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner keyboard = new Scanner(System.in);
        System.out.println("Enter Binary Number Please:");
        String aString = keyboard.next();
        int sizeOf = aString.length();
        int[] binArray = new int[sizeOf];
        char digitBin = ' ';
        int digitChar = 0;
        for(int i = 0; i < sizeOf; i++){
            digitBin = aString.charAt(0);
            digitChar = Character.getNumericValue(digitBin);
            binArray[i] = digitChar;
        }
        int total = 0;
        int multiplyNum = 1;
        for(int i = sizeOf - 1; i > -1; i--){
            total = (binArray[i] * multiplyNum) + total;
            multiplyNum = multiplyNum * 2;
        }
        System.out.println(total);

    }

}

If you dont know Arrays that well and all of your loops - better start practicing... You will use them a ton in school!

Comments