[英]Input from text file to array
输入将是一个文本文件,其中包含0-9的任意数量的整数,并且没有空格。 如何使用这些整数填充数组,以便稍后对其进行排序?
我到目前为止的内容如下:
BufferedReader numInput = null;
int[] theList;
try {
numInput = new BufferedReader(new FileReader(fileName));
} catch (FileNotFoundException e) {
System.out.println("File not found");
e.printStackTrace();
}
int i = 0;
while(numInput.ready()){
theList[i] = numInput.read();
i++;
显然,该列表尚未初始化,但我不知道它的长度是多少。 另外,我不太确定如何做到这一点。 感谢您的任何帮助。
为了澄清输入,它看起来像:1236654987432165498732165498756484654651321我不知道长度,我只想要单个整数字符,而不是多个。 所以0-9,而不是0-10像我之前不小心说的那样。
去收集API即ArrayList
ArrayList a=new Arraylist();
while(numInput.ready()){
a.add(numInput.read());
}
您可以使用List<Integer>
而不是int[]
。 使用List<Integer>
,您可以根据需要添加项目, List
将随之增长。 如果完成,可以使用toArray(int[])
方法将List
转换为int[]
。
1。 使用guava很好地将文件的第一行读入1个String
2。 将该String转换为char数组 - 因为所有数字都是一位数字,所以它们实际上是char
3。 将字符转换为整数。
4。 将它们添加到列表中。
public static void main(String[] args) {
String s = "1236654987432165498732165498756484654651321";
char[] charArray = s.toCharArray();
List<Integer> numbers = new ArrayList<Integer>(charArray.length);
for (char c : charArray) {
Integer integer = Integer.parseInt(String.valueOf(c));
numbers.add(integer);
}
System.out.println(numbers);
}
打印: [1, 2, 3, 6, 6, 5, 4, 9, 8, 7, 4, 3, 2, 1, 6, 5, 4, 9, 8, 7, 3, 2, 1, 6, 5, 4, 9, 8, 7, 5, 6, 4, 8, 4, 6, 5, 4, 6, 5, 1, 3, 2, 1]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.