我一直在尝试创建一个Java程序来读取包含100个整数的文件“100.txt”,然后将它们存储到int数组中。稍后,我将让它打印数组并对数组中的数字进行排序,但我想让它读取文本文件并将数字存储在数组中,然后首先将其转换为 int 数组。我该怎么做?
我尝试了一些不同的事情。我知道如何从扫描仪读取文本文件并创建数组,但我从未更改过类型(在本例中为 String 到 int)。如果你们中的任何人可以帮助并给我一些关于如何解决这个问题的指示,我将不胜感激。
try
{
File file = new File("100.txt");
Scanner input = new Scanner(file);
while (input.hasNextLine())
{
String line = input.nextLine();
System.out.println(line);
}
input.close();
}
catch (Exception ex)
{
ex.printStackTrace();
}
int[] array = new int[file.length];
int i, n = array.length;
for (i = 0; i < n; i++)
{ array[i] = Integer.parseInt(file[i]);
}
}
最佳答案
假设您知道文件的行数,则可以使用此代码。另请注意,将其作为 BufferedReader 读取并将其传递给扫描仪会更有效。
我已尽力使其尽可能简单,但如果您有任何疑问,请随时询问。
public int[] readFile(String filePath)throws Exception
{
int[] array = new int[100];
Scanner sc = new Scanner(new BufferedReader(new FileReader(new File(filePath))));
for(int i=0;sc.hasNextLine();i++)
{
array[i]=Integer.parseInt(sc.nextLine());
}
return array;
}
关于java - 如何从扫描仪读取文本文件并转换为 Int 数组 Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55643905/