如何解决如何从文本文件在数组中插入和保存数据? 在Java中
如何在数组中插入以下数据,以便获取这些元素在数组中的位置?
1 37
4 10
9 22
21 21
28 56
36 8
51 16
71 20
80 20
98 -20
95 -20
93 -20
87 -63
64 -4
62 -43
56 -3
49 -38
47 -21
16 -10
所以我尝试了这个:
int[] gameBoard;
String fileName;
Scanner in = new Scanner(new File("p3input.txt"));
fileName="in.txt";
int numLadders = 0;
int numChutes = 0;
int blank=0;
int index=0;
int value;
index = in.nextInt();
gameBoard = new int[index];
while (in.hasNextInt()) {
index = in.nextInt();
value = in.nextInt();
gameBoard[index] = value;
if (value > 0) {
numLadders++;
}
else if(value < 0) {
numChutes++;
}
else {
blank++;
}
}
但我想从该文件中读取并获取数组中的元素,例如:array[4,10,5,6]
。
解决方法
输入文件包含两列 index
和 value
,现有代码创建一个空数组 gameBoard
并将值保存在适当的索引处,因此结果数组如下所示:>
[0,37,10,22,... ]
此外,这里初始 index
应该是 99 - 第一列中的最大数字 (98) + 1,因为数组索引从 0 开始,并且 gameBoard
将是稀疏的并且包含许多零。
如果要将索引和值都存储在同一个 gameBoard
数组中,则游戏板的大小应等于对数的两倍(对于给定示例 2 * 19 = 38
)
index = 2 * in.nextInt(); // number of pairs
gameBoard = new int[index];
index = 0;
boolean readValue = false;
while (in.hasNextInt() && index < gameBoard.length) {
gameBoard[index] = in.nextInt();
if (readValue) {
value = gameBoard[index];
if (value > 0) {
numLadders++;
}
else if(value < 0) {
numChutes++;
}
else {
blank++;
}
}
index++;
readValue = !readValue;
}
在这种情况下,gameBoard
将如下所示:
[1,4,9,21,28,56,...
此外,对于 Map<Integer,Integer>
使用 gameBoard
而不是数组可能会更好,因为它允许通过“索引”键快速访问:
{1=37,4=10,9=22,21=21,28=56,... }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。