-2

I have a text file that has lines of 1's and 0's. However it's printing gibberish when I want the actual number, I think it is loaded in the array correctly but it's not printing.

10100010
10010010
10110101
11100011
10010100
01010100
10000100
11111111
00010100

Code:

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;

public class Encoder {

    public static void main(String[] args) {
        System.out.println("Please enter file Name: ");

        Scanner getInput = new Scanner(System.in);
        String fileName = getInput.nextLine();

        File file = new File(fileName + ".txt");
        FileInputStream fstream = null;

        try {

            fstream = new FileInputStream(file);

            DataInputStream in = new DataInputStream(fstream);

            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            String strLine;

            while ((strLine = br.readLine()) != null) {
                // print the content to console
                System.out.println(strLine);
                int[] n1 = new int[8];

                for (int i = 0; i < 7; i++) {
                    System.out.println((strLine.charAt(i)));
                    n1[i] = strLine.charAt(i + 1);

                }
                for (int n : n1) {
                    System.out.println(n + " ");
                }

                ArrayList al = new ArrayList();
            }

            in.close();

        } catch (Exception e) {// Catch exception if any
            System.err.println("Error: " + e.getMessage());
        }

        System.out.println("Even or Odd");
    }
}
njzk2
  • 37,030
  • 6
  • 63
  • 102

2 Answers2

0

You are printing the integer value of the characters 0,1 which evaluate to 48 and 49 respectively.

n1[i] = strLine.charAt(i + 1);//casts the character to an int here

Create an array of characters, not ints.

I.e.

char[] n1 = char int[8];

instead of

int[] n1 = new int[8];
C.B.
  • 7,548
  • 5
  • 16
  • 32
0

You have an int array. You are getting a char from the string. That char is an unsigned 16 bit int, and contains a numerical value used to map to a character set. For US_ASCII/UTF-8 this means 48 for the character '0' and 49 for the character '1'. When you assign that to an int in your array, that's what you get.

If you want the integer value represented by each character in the string (0 or 1), the easiest way would be to simply do:

n1[i] = Integer.valueOf(strLine.substring(i, i+1));

The Integer class provides a static method for converting a String representation of a integer to an Integer (which of course unboxes to an int). String.substring() returns a String rather than a char.

Brian Roach
  • 72,790
  • 10
  • 128
  • 154