在java中读取文件时显示错误的输出
运行此程序会显示错误的输出。我的文件“values.txt”包含在java中读取文件时显示错误的输出,java,Java,运行此程序会显示错误的输出。我的文件“values.txt”包含45678和输出 运行后,程序为00000 import java.util.Scanner; public class array{ public static void main(String[] args)throws IOException { final int SIZE = 6; int[] numbers = new int[SIZE]; int inde
45678
和输出运行后,程序为
00000
import java.util.Scanner;
public class array{
public static void main(String[] args)throws IOException
{
final int SIZE = 6;
int[] numbers = new int[SIZE];
int index = 0;
File fl = new File("values.txt");
Scanner ab = new Scanner(fl);
while(ab.hasNext() && index < numbers.length)
{
numbers[index] = ab.nextInt();
index++;
System.out.println(numbers[index]);
}
ab.close();
}
}
import java.util.Scanner;
公共类数组{
公共静态void main(字符串[]args)引发IOException
{
最终整数大小=6;
int[]数字=新的int[大小];
int指数=0;
文件fl=新文件(“values.txt”);
扫描仪ab=新扫描仪(fl);
while(ab.hasNext()&&index
首先分配给数字[索引]
,然后增加索引
,并输出数字[索引]
(用于下一个空值)
交换
index++
和System.out
调用。将index++
移动到System.out.println
调用之后
此时,您总是输出一个未赋值的值numbers
。(在Java中,int
数组中的每个元素都初始化为零)
另一种选择是放弃
index++完全编码>并写入System.out.println(数字[index++])代码>。我个人觉得这更清楚。用while(ab.hasNext()&&index)替换while循环