Issue
Hi I am new on programing and I am having a problem I am trying to copy some things from a file to a array
and I just want to copy in the position 1,2,3 and 4 from the file. Example copy to the array 11 , G , 0 , 20
.
String[][] aa = new String[100][6];
try {
Scanner x = new Scanner(new File("Turmas.txt"));
x.useDelimiter("[;\n]");
for (int i = 0; i < 100; i++) {
for (int j = 0; j < 6; j++) {
if (x.hasNext()) {
aa[i][j] = x.next();
}
}
}
x.close();
} catch (FileNotFoundException ex) {
JOptionPane.showMessageDialog(
null, "An error occurred, try restarting the program!",
"ERROR!", JOptionPane.ERROR_MESSAGE
);
}
String[][] aaa = new String[100][4];
for (int i = 0; i < 100; i++) {
for (int j = 0; j < 4; j++) {
if (aa[i][j] == null) {
System.out.println("null " + i + " " + j);
}
else {
if (aa[i][0].equals(String.valueOf(SAVEID))) {
aaa[i][j] = aa[i][1];
aaa[i][j + 1] = aa[i][2];
aaa[i][j + 2] = aa[i][3];
aaa[i][j + 3] = aa[i][4];
}
}
}
}
System.out.println(aaa[0][0]);
System.out.println(aaa[0][1]);
System.out.println(aaa[0][2]);
System.out.println(aaa[0][3]);
Solution
If only 4 values are needed from the input array are needed, why not just read these specific values?
String[] result = new String[4];
try (Scanner input = new Scanner(new File("Turmas.txt")) // input closed automatically
.useDelimiter(";|\\R") // use character class \R to match line-feed characters
) {
if (input.hasNext()) {
input.next(); // skip the 1st token
for (int i = 0; i < result.length && input.hasNext(); i++) {
result[i] = input.next();
}
}
} catch (FileNotFoundException ex) {
JOptionPane.showMessageDialog(
null, "An error occurred, try restarting the program!",
"ERROR!", JOptionPane.ERROR_MESSAGE
);
}
If it is needed to read the columns with indexes [1..4]
from the file containing 6 columns per line, it is cleaner to read the source file line by line, split each line by ;
, skip 1 column with index 0, and keep the 4 columns.
String[][] result = new String[100][4];
try (Scanner input = new Scanner(new File("Turmas.txt"))) {
for (int i = 0; i < result.length && input.hasNextLine(); i++) {
String[] parts = input.nextLine().split(";");
for (int j = 1; j < Math.min(result[i].length, parts.length); j++) {
result[i][j - 1] = parts[j];
}
}
} catch (FileNotFoundException ex) {
JOptionPane.showMessageDialog(
null, "An error occurred, try restarting the program!",
"ERROR!", JOptionPane.ERROR_MESSAGE
);
}
Answered By - Alex Rudenko
Answer Checked By - Willingham (JavaFixing Volunteer)