Home > Software engineering >  Converting Binary to Decimal using a text file
Converting Binary to Decimal using a text file

Time:10-03

I'm creating a program made up of two java files. The first one involves creating a class that accepts a binary from the user and returns its decimal value. The second involves creating a class that reads a list of binary strings from a text file and writes their decimal values to the console. This class should call methods from the first java class in order to achieve its tasks, and should be able to indicate if one of the strings in this file is not binary.

I have the first java class completed, but I'm having difficulty on the second, specifically on how I can get the program to read each individual String from the text file and then either print out their values or declare that they are not a binary. I also need some help on how to call methods from the first class. Could someone help lead me in the right direction?

Here are both codes:

Class 1:

import java.util.*;
public class BinaryDecoder {

    public static void main(String[] args) {
        
        Scanner input = new Scanner(System.in);
        
        System.out.print("Enter a binary: ");
        String binary = input.nextLine();
        
        System.out.println("---------------");
        
        boolean isBinary = binaryDetector(binary);
        
        if(isBinary) {
            int count = 0;
            for(int i=0; i<binary.length(); i  ) {
                if(binary.charAt(i) != ' ') {
                    count  ;
                }
            }
            int binarySize = Integer.valueOf(count);
            System.out.println("Binary size: "   binarySize);
            
            int decimalValue = binaryToDecimal(binary);
            
            System.out.println("Value = "   decimalValue);
        }
        else {
            System.out.println("Not a binary");
        }
        
    }
    
    public static boolean binaryDetector(String x) {
        int copyOfInput = Integer.valueOf(x);
        
        while(copyOfInput != 0) {
            if(copyOfInput % 10 > 1) {
                return false;
            }
            copyOfInput = copyOfInput/10;
        }
        return true;
        }
    
    public static int binaryToDecimal(String n) {
        String num = n;
        int dec_value = 0;
        
        int base = 1;
        
        int len = num.length();
        for(int i = len - 1; i>= 0; i--) {
            if(num.charAt(i) == '1') {
                dec_value  = base;
            }
            base = base * 2;
        }
        return dec_value;
    }

}

Class 2

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class BinaryToDecimalTester {
    public static void main(String[] args) throws Exception{
        Scanner inFile = new Scanner(new File("Strings.txt"));
        while(inFile.hasNext()) {
            String inString = inFile.next();
}
}
}

And let's say for reference that the text file has these numbers in it:

1011010011101
1011101110101
1201234000100
1234456000110
1011010100011

Please let me know if you need any more clarification or information. Thank you all very much!

CodePudding user response:

In order to use methods from BinaryDecoder in BinaryToDecimalTester you will have to import them. The best way would be to declare package in each class and import that using it, for example Decoder class:

package binarynumbers;

import java.util.*;
public class BinaryDecoder {

public static void main(String[] args) { ...

and then import specific ( or all ) methods in BinaryToDecimalTester:

package stackoverflow;


import java.io.File;
import java.util.Scanner;

import static stackoverflow.BinaryDecoder.binaryToDecimal;

public class BinaryToDecimalTester { ...

importing it this way lets you use it normally as you woud expect :

System.out.println(binaryToDecimal(inString));

Concept of packages and imports is more complicated than this and essential to writing programs.

As to reading each individual line as String from the text file and processing it your class is sufficient, FileInputReader is one of another options to read from file. My example would be this:

package binarynumbers;


import java.io.BufferedReader;
import java.io.FileReader;

import static binarynumbers.BinaryDecoder.binaryToDecimal;
import static binarynumbers.BinaryDecoder.binaryDetector;

public class BinaryToDecimalTester {
    public static void main(String[] args) throws Exception{
    BufferedReader br = new BufferedReader(new FileReader("Strings.txt"));
    String line = "";

    while ((line = br.readLine()) != null)
    {
        System.out.println(binaryDetector(line));
        System.out.println(binaryToDecimal(line));
    }
}

}

CodePudding user response:

You have to select which class should be your main.

If you keep 2 as your main and then instead of main in 1 you can read both files in 2 and used the static methods you have created in 1 by importing them in 2.

import BinaryDecoder.binaryToDecimal;

CodePudding user response:

I would recommend you do the check for a binary digit as you try to convert the value. Then throw an exception and print the message if the digit is not binary.

There is no need to first check and then convert the value.

Here is an easy way to do the conversion.

public static int binaryToDecimal(String n) {
   int val = 0;
   for(char c : n.toCharArray()) {
       if (c != '1' && c != '0') {
           throw new IllegalArgumentException("Number not binary");
       }
       val = val*2;
       val  = c-'0';
   }
   return val;
}

Now all you need to do is read in the values and call the method. In lieu of the exception you could also return an optional.

public static OptionalInt binaryToDecimal(String n) {
   int val = 0;
   for(char c : n.toCharArray()) {
       if (c != '1' && c != '0') {
           return OptionalInt.empty();
       }
       val = val*2;
       val  = c-'0';
   }
   return OptionalInt.of(val);
}

Now just check to see if the returned Optional is empty before you print the result.

String[]  test = { 
    "92282",
    "1010101111",
    "1111001",
    "111112111"
};

for (String str : test) {
    OptionalInt op = binaryToDecimal(str);
    System.out.printf("%s -> %s%n", str, op.isPresent() ?
             op.getAsInt() : "Non binary string");
}

prints

92282 -> Non binary string
1010101111 -> 687
1111001 -> 121
111112111 -> Non binary string
  • Related