早安绅士,
我在为另一个项目转换一些代码时遇到了一个问题,并希望得到一些帮助。在'readFile'方法中,我试图在读取文件时将String解析为整数。但是,它给了我错误'array found,但int required'
感谢任何帮助,
祝你好运 麦克
import java.util.*;
import java.io.*;
public class JavaApplication1
{
static int [] matrix = new int [10];
static Scanner input = new Scanner(System.in);
public static void main(String[] args) throws IOException
{
String fileName = "Integers.txt";
// read the file
readFile(fileName);
// print the matrix
printArray(fileName, matrix);
}
// Read File
public static void readFile(String fileName) throws IOException
{
String line = "";
FileInputStream inputStream = new FileInputStream(fileName);
Scanner scanner = new Scanner(inputStream);
DataInputStream in = new DataInputStream(inputStream);
BufferedReader bf = new BufferedReader(new InputStreamReader(in));
int lineCount = 0;
String[] numbers;
while ((line = bf.readLine()) != null)
{
numbers = line.split(" ");
for (int i = 0; i < 10; i++)
{
matrix[lineCount][i] = Integer.parseInt(numbers[i]);
}
lineCount++;
}
bf.close();
}
public static void printToFile(String fileName, String output) throws IOException
{
java.io.File file = new java.io.File(fileName);
try (PrintWriter writer = new PrintWriter(file))
{
writer.print(output);
}
}
public static void printArray(String fileName, int [] array)
{
System.out.println("The matrix is:");
for (int i = 0; i < 10; i++)
{
System.out.println();
}
System.out.println();
}
}
答案 0 :(得分:3)
matrix
是一个int
类型的数组,这意味着matrix[lineCount]
是一个int。
你正在尝试做matrix[lineCount][i]
,它正在获得int的位置。
这就是你得到这个错误的原因。
我猜您希望矩阵为int[][] matrix = new int[10][10];
答案 1 :(得分:1)
matrix[lineCount][i] = Integer.parseInt(numbers[i]);
错了。
应该是
matrix[lineCount]= Integer.parseInt(numbers[i]);
OR
matrix[i]= Integer.parseInt(numbers[i]);