Purple_Rain
Purple_Rain

Reputation: 77

Reading from a file rather than from the console

I am getting exception thrown and i think it has to with the ArrayIndexOutOfBounds at the sub string and also do you think the below method would work for getting data passed to my array after parsing

I want this to be read from a txt file like this, on each line:

  1
  0
  1
  0
  0
  1
  0

ONE INTEGER PER LINE!!

String fileName = "input.txt";
File file = new File(fileName);
Scanner scanner = new Scanner(file);

while(scanner.hasNextLine()){
    data1 = scanner.nextLine();

}
for ( int i = 0; i < data1.length(); i++)
{
    covertDataArray[i] = Byte.parseByte(data1.substring( i, i+1));
}

This is previous working version but it reads from the console. where it would be : 1010101001

System.out.println("Enter the binary bits");

data1 = in.next();


for ( int i = 0; i < data1.length(); i++)
{
    covertDataArray[i] = Byte.parseByte(data1.substring( i, i+1));
}

Upvotes: 0

Views: 56

Answers (1)

Joffrey
Joffrey

Reputation: 37660

You're reading all the lines and only keeping the last in your data1 variable. That's probably your problem.

You should, instead, handle each value right away while reading the file, and build an ArrayList instead of an array (because you won't know its size beforehand):

String fileName = "input.txt";
File file = new File(fileName);
Scanner scanner = new Scanner(file);

ArrayList<Byte> covertDataList= new ArrayList<>();
while(scanner.hasNextLine()){
    String line = scanner.nextLine(); // the line should be just a number
    covertDataList.add(Byte.parseByte(line)); // no substring needed
}

If you want to fail nicely when the file format is wrong, you may surround parseByte with a try/catch block.

About the ArrayList

If you want to use your list as an array, you can just:

  • use covertDataList.get(i) instead of covertDataArray[i]
  • use covertDataList.set(i, value); instead of covertDataArray[i] = value;

If you really need an array (I don't see the point here), you can do this:

Byte[] covertDataArray = covertDataList.toArray(new Byte[list.size()]);

Upvotes: 1

Related Questions