Reputation: 433
I need to store data from an input file that has the following form:
k=5
1: 62 35
2: 10 49
1 Banana
2 Apple
I need to store the value for k as an int, and then I need to store the int values of the next two lines as an [2][2]-array, and finally I need the strings "Banana" and "Apple" to be stored in a list. I tried using the useDelimiter but it ignores my delimiters and reads whole lines as one line instance.
public static void main(String[] args) {
File file = new File("input.text");
try {
Scanner scanner = new Scanner(file);
scanner.useDelimiter("n=");
scanner.useDelimiter(".:");
int k = scanner.nextLine();
for (int i = 0; i < 2; i++)
for (int j = 0; j < 2; j++)
array[i][j] = scanner.nextInt();
}
} scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
Upvotes: 2
Views: 1007
Reputation: 21004
If the text always have the same structure, then you could do
int k = Integer.parseInt(scanner.nextLine().substring("=")[1]);
String currentLine;
for (int i = 0; i < 2; i++)
currentLine = scanner.nextLine().substring(currentLine.indexOf(" ") + 1)
for (int j = 0; j < 2; j++)
array[i][j] = currentLine.split(" ")[j];
}
}
Then for the Banana and Apple parsing, apply the same logic. Substring until from the index of the first space + 1 character as we don't want to keep it. Then add that string to your list.
Upvotes: 1