gpt4 book ai didi

java - 从数组中读取数字,但它只显示 0

转载 作者:行者123 更新时间:2023-11-30 08:07:59 26 4
gpt4 key购买 nike

我想做的是将文本文件放入矩阵数组中,然后显示所有数字。我用它来显示数字,但它们都是零。

这是我的代码:

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class is12177903
{
public static int[][] read_input(String filename) throws FileNotFoundException
{
int matrix [][] = null;

BufferedReader buffer = new BufferedReader(new FileReader(filename));
String line;
int row = 0;
int size = 0;
try {
while ((line = buffer.readLine()) != null)
{
String[] vals = line.trim().split("\\s+");


if (matrix == null)
{
size = vals.length;

matrix = new int[size][size];
}

for (int col = 0; col < size; col++)
{
matrix[row][col] = Integer.parseInt(vals[col]); //this is line 31
}

row++;
}
} catch (NumberFormatException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
}

return matrix;

}

public static void printMatrix(int[][] matrix)
{
String str = "";
int size = matrix.length;


if (matrix != null) {
for (int row = 0; row < size; row++)
{
str += " ";
for (int col = 0; col < size; col++)
{
str += String.format("%2d", matrix[row][col]);
if (col < size - 1)
{
str += "";
}
}
if (row < size - 1)
{
str += "\n";


}
}
}

System.out.println(str);
}

public static void main(String[] args)
{
int[][] matrix = null;

try {
matrix = read_input("AI2015.txt"); // this is line 83
} catch (Exception e) {
e.printStackTrace();
}

printMatrix(matrix);

}
}

我正在读取的文本文件只有 26x26,整数为 1 或 0。

我每次运行它时都会出现一些错误,我不确定它们是什么意思:java.lang.NumberFormatException:对于输入字符串:“0”

在 java.lang.NumberFormatException.forInputString(未知来源)

在 java.lang.Integer.parseInt(未知来源)

在 java.lang.Integer.parseInt(未知来源)

在 is12177903.read_input(is12177903.java:31)

在 is12177903.main(is12177903.java:83)

最佳答案

您的文件保存在UTF-8byte order mark 编码( Material list )!

UTF-8 字节顺序标记正好由三个字节组成:0xEF 0xBB 0xBF。您正在实例化一个 FileReader,它将使用平台默认编码。在许多情况下,这是 ISO-8859-1。您看到的字符是这三个字节的 ISO-8859-1 字符。显然它们是无效输入。

有两种解决方法:

  1. 删除 BOM。 UTF-8 BOM 实在是太难用了,有很多程序无法处理它。所以最好不要拥有它。

  2. 按照@budi 的回答,使用 InputStream 将编码设置为 UTF-8。

关于java - 从数组中读取数字,但它只显示 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33376495/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com