views:

119

answers:

6

Hey hey there.

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;
}
+9  A: 

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

AraK
Oh crap. That was incredibly simple. Thank you a million times. Hopefully this will be helpful for someone else if they google it :x
alainmeyer1
+4  A: 

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

Chris Jester-Young
+4  A: 

The int type has no concept of leading zeroes.

To add leading zeroes for display, use one of the format methods:

System.out.format("%04d", 80);
McDowell
A: 

Integers cannot have leading zeros. You could store the student ID as a String instead.

Tim Cooper
A: 

Integer.parseInt(tokens.nextToken()); will return the integer, so leading zeros will be omitted.

fastcodejava
A: 

Have a look to the DecimalFormat class to handle parsing/formating of numbers.

Guillaume