【发布时间】:2016-05-03 18:50:45
【问题描述】:
这个文件从一个只有一行的文本文件中读取:
7319812227725338960527291316
输出是:
Reading input values from text.txt
731
981
222
772
533
89
60
527
291
316
问题是程序如何给出这个输出?我不知道它是如何在每个数组单元格中存储 3 位数字的?
我还注意到,当我将 txt 文件的内容复制到 Word 时,它会粘贴此内容
7319812227725338960527291316
进入一列:
731
981
222
772
533
89
60
527
291
316
文本文件来自我的老师。但是当我创建自己的文本文件并放置一个像 123 456 789 这样的数字时,输出是有意义的,因为 txt 文件中的数字用空格分隔,因此每个数字都将分配给一个数组单元格。
import java.util.Scanner;
import java.util.Vector;
import java.util.Arrays;
import java.io.File;
public class test{
public static void main(String[] args){
Scanner s;
if (args.length > 0){
try{
s = new Scanner(new File(args[0]));
} catch(java.io.FileNotFoundException e){
System.out.printf("Unable to open %s\n",args[0]);
return;
}
System.out.printf("Reading input values from %s.\n",args[0]);
}else{
s = new Scanner(System.in);
System.out.printf("Enter a list of non-negative integers. Enter a negative value to end the list.\n");
}
Vector<Integer> inputVector = new Vector<Integer>();
int v;
while(s.hasNextInt() && (v = s.nextInt()) >= 0)
inputVector.add(v);
int[] array = new int[inputVector.size()];
for (int i = 0; i < array.length; i++){
array[i] = inputVector.get(i);
System.out.println(array[i]);
}
}
}
【问题讨论】:
-
这可能是您在 Windows 记事本中打开的测试文件无法正确处理换行符 (
\n)。