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;
}
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With