Well, I am attempting to read a text file that looks like this:
FTFFFTTFFTFT
3054 FTFFFTTFFTFT 4674 FTFTFFTTTFTF ... etcAnd when I am reading it, everything compiles and works wonderfully, putting everything into arrays like this:
studentID[0] = 3054
studentID[1] = 4674 ... etcstudentAnswers[0] = FTFFFTTFFTFT
studentAnswers[1] = FTFTFFTTTFTFHowever, 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];
St开发者_开发百科ring 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;
}
Use String
instead of int
. As a general rule, use integral types for calculations.
If you want to preserve the zeroes, don't use parseInt
on the student IDs; just store them as strings.
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);
Integer.parseInt(tokens.nextToken());
will return the integer, so leading zeros will be omitted.
Have a look to the DecimalFormat class to handle parsing/formating of numbers.
精彩评论