Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my array deleting the zeroes from a file I am reading?

Tags:

java

arrays

Well, I am attempting to read a text file that looks like this:

FTFFFTTFFTFT
3054 FTFFFTTFFTFT
4674 FTFTFFTTTFTF
... etc

And when I am reading it, everything compiles and works wonderfully, putting everything into arrays like this:

studentID[0] = 3054
studentID[1] = 4674
... etc

studentAnswers[0] = FTFFFTTFFTFT
studentAnswers[1] = FTFTFFTTTFTF

However, if the studentID has a leading or trailing zero, when I print it with System.out.println();, it deletes the leading and trailing zeroes! I have a feeling this is something simple, and I need to like copy the array or something. Thank you :)

Below is my code:

public static String[] getData() throws IOException {
  int total = 0;
  int[] studentID = new int[127];
  String[] studentAnswers = new String[127];

  String line = reader.readLine();
  String answerKey = line;
  StringTokenizer tokens;
  while((line = reader.readLine()) != null) {
    tokens = new StringTokenizer(line);
    studentID[total] = Integer.parseInt(tokens.nextToken());
    studentAnswers[total] = tokens.nextToken();
    System.out.println(total + " " +studentID[total]);
    total++;
  }
  return studentAnswers;
}
like image 974
ashamadelion Avatar asked Feb 01 '10 14:02

ashamadelion


People also ask

How do you keep leading zeros in Java?

You just need to add "%03d" to add 3 leading zeros in an Integer. Formatting instruction to String starts with "%" and 0 is the character which is used in padding. By default left padding is used, 3 is the size and d is used to print integers.

How do you remove zeros from an array?

Approach: Mark the first non-zero number's index in the given array. Store the numbers from that index to the end in a different array. Print the array once all numbers have been stored in a different container.


2 Answers

Use String instead of int. As a general rule, use integral types for calculations.

like image 62
Khaled Alshaya Avatar answered Sep 20 '22 16:09

Khaled Alshaya


If you want to preserve the zeroes, don't use parseInt on the student IDs; just store them as strings.

like image 43
Chris Jester-Young Avatar answered Sep 19 '22 16:09

Chris Jester-Young