【发布时间】:2014-03-25 10:54:09
【问题描述】:
我在存储文件中的值时遇到问题。
3
10 2
100 35
5 4
17 20 3 5
6 10
6 9 12 15 18 21 24 27 30 33
我希望将第一行存储为整数,将具有多个值的其他行存储为单独的 int 数组。
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("candy.dat"));
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
还有其他方法吗?谢谢
编辑:基本上第一个整数(在这个例子中是 3)将代表有多少测试用例要遵循。每个测试用例后跟两行。所以第一个测试用例是 [10, 2] [100, 35]。
EDIT2:如果有人想知道,我设法解决了我的问题。 这是我的代码
Scanner sc = new Scanner(new File("candy.dat"));
String testCase = sc.nextLine();
String[] numOfCandy = new String[0];
String[] NK = new String[0];
for (int i = 0; i < Integer.parseInt(testCase); i++) {
System.out.println("test case " + (i+1));
NK = sc.nextLine().split(" ");
numOfCandy = sc.nextLine().split(" ");
//System.out.println(NK[0] + " " + NK[1]);
//System.out.println(numOfCandy[0] + " " + numOfCandy[1]);
find(NK[0], NK[1], numOfCandy); //method to solve problem
}
我首先存储了测试用例的值,即 3,以告诉 for 循环运行多少次。
我实例化了 2 个字符串数组供以后使用。
在 for 循环中,我读取下一行并将其拆分存储到字符串数组 NK,然后将其后的行存储到 numOfCandy。
从那里,我能够成功地从数组中检索数据来解决我的问题。
【问题讨论】:
-
你的问题不是很清楚。您有一定程度的工作代码,但似乎您没有尝试进一步使用该解决方案。你到底坚持哪一点?
-
如果我站在你的立场上,我会将这些数据存储在一些定义明确的结构中,并以 JSON 字符串的形式保存/检索。 2c.