【发布时间】:2014-12-10 17:06:33
【问题描述】:
我有一个这样的文件
test.txt:
122352352246
12413514316134
现在我想一次读取每个数字,并将其作为一个元素存储在一个列表中。 我尝试使用扫描仪。但它每次都会读取一行,并输出一个长整数。这意味着如果我想获得数字,我需要进一步分隔该整数中的数字。我想必须有一种优雅的方式来每次直接读取一个数字。下面是我的代码
public class readDigits {
public static void main(String[] args) throws IOException{
List<Integer> list = new ArrayList<Integer>();
File file = new File("test.txt");
Scanner in = new Scanner(file);
int c;
try {
while (in.hasNext()){
c = in.nextInt();
list.add(c);
}
}
finally {
System.out.println(list);
in.close();
}
}
}
【问题讨论】:
-
这看起来可能对您有所帮助。 stackoverflow.com/questions/13942701/…
-
@zhang_rick 您可以使用方法 charAt() 一次读取一个字母/数字
标签: java