[英]Input from text file to array
The input will be a text file with an arbitrary amount of integers from 0-9 with NO spaces. 输入将是一个文本文件,其中包含0-9的任意数量的整数,并且没有空格。 How do I populate an array with these integers so I can sort them later?
如何使用这些整数填充数组,以便稍后对其进行排序?
What I have so far is as follows: 我到目前为止的内容如下:
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++;
Obviously theList isn't initialized, but I don't know what the length will be. 显然,该列表尚未初始化,但我不知道它的长度是多少。 Also I'm not too sure about how to do this in general.
另外,我不太确定如何做到这一点。 Thanks for any help I receive.
感谢您的任何帮助。
To clarify the input, it will look like: 1236654987432165498732165498756484654651321 I won't know the length, and I only want the single integer characters, not multiple. 为了澄清输入,它看起来像:1236654987432165498732165498756484654651321我不知道长度,我只想要单个整数字符,而不是多个。 So 0-9, not 0-10 like I accidentally said earlier.
所以0-9,而不是0-10像我之前不小心说的那样。
Going for Collection API ie ArrayList 去收集API即ArrayList
ArrayList a=new Arraylist();
while(numInput.ready()){
a.add(numInput.read());
}
You could use a List<Integer>
instead of a int[]
. 您可以使用
List<Integer>
而不是int[]
。 Using a List<Integer>
, you can add items as desired, the List
will grow along. 使用
List<Integer>
,您可以根据需要添加项目, List
将随之增长。 If you are done, you can use the toArray(int[])
method to transform the List
into an int[]
. 如果完成,可以使用
toArray(int[])
方法将List
转换为int[]
。
1 . 1。 Use guava to nicely read file's 1st line into 1
String
使用guava很好地将文件的第一行读入1个
String
2 . 2。 convert that String to char array - because all of your numbers are one digit lengh, so they are in fact
char
s 将该String转换为char数组 - 因为所有数字都是一位数字,所以它们实际上是
char
3 . 3。 convert chars to integers.
将字符转换为整数。
4 . 4。 add them to list.
将它们添加到列表中。
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);
}
prints: [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]
打印:
[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.