繁体   English   中英

如何从文本文件中插入和保存数组中的数据? (在Java中)

[英]How to insert and save data in an array from a Text file? ( In 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]

输入文件包含两列indexvalue ,现有代码创建一个空数组gameBoard并将值保存在适当的索引处,因此结果数组如下所示:

[0, 37, 0, 0, 10, 0, 0, 0, 0, 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, 37, 4, 10, 9, 22, 21, 21, 28, 56, ...

此外,最好使用Map<Integer, Integer>而不是数组作为gameBoard ,因为它允许通过“索引”键快速访问:

{1=37, 4=10, 9=22, 21=21, 28=56, ... }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM