将每行从整数列表转换为整数数组? [英] Converting each line from a list of integers into an array of integers?
问题描述
我是Java新手,如果其中任何一个不清楚,我们深表歉意-我想将四位数整数列表转换为整数数组列表-即,如果我有一个4567的整数,我想将其转换为四个独立整数的数组[4、5、6、7].因此,我想将列表的每一行/索引转换为它自己的数组(而不是将整个列表转换为数组).我目前正在读取一个包含四位数整数的文件(每个文件都在新行上)并将其添加到列表中,然后该列表返回该列表-有关如何编码以使其返回整数列表的任何想法而不是数组?
I'm new to Java, so apologies if any of this is unclear - I want to convert a list of four-digit integers into a list of integer arrays - i.e if I have an integer that is 4567, I want to convert that into an array of four separate integers [4, 5, 6, 7]. So I want to convert each line/index of the list into it's own array (rather than converting the entire list into an array). I'm currently reading a file that has four-digit integers (each on a new line) and adding them to a list, which is then returning that list - any ideas on how could I code it so that it returns a list of integer arrays instead?
public List <Integer> loadGuesses (String fileName){
List<Integer> loadGuessList = new ArrayList<>();
try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
String line;
while ((line = reader.readLine()) != null) {
loadGuessList.add(Integer.parseInt(line));
}
} catch (FileNotFoundException f){
System.out.println("File not found - please re-enter with correct file name.");
getPlayerFile();
} catch (IOException e){
System.out.println("Incorrect file name - Please re-enter with correct file name.");
getPlayerFile();
}
return loadGuessList;
}
推荐答案
将loadGuessList
的类型更改为List<int[]>
.
读取字符串后,您可以遍历字符并将每个字符转换为整数.
After reading the string, you can iterate through the characters and convert each to an int.
List<int[]> loadGuessList = new ArrayList<>();
while ((line = reader.readLine()) != null) {
int [] digits = new int[4];
for (int i = 0; i < line.length(); i++) { //Assuming line.length() will be 4
digits[i] = line.charAt(i) - '0';
}
loadGuessList.add(digits);
}
这篇关于将每行从整数列表转换为整数数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!