我试图创建一个将从文件中读取文本并将其放入数组的类,并且我遇到了一个我们尚未在课堂上讨论的错误......
这是我的代码
import java.util.Scanner;
import java.io.*;
class Card
{
File inputFile = new File("Cards.txt");
Scanner textScan = new Scanner(inputFile);
{
String[] cards = new String[51];
for (int i = 0; i < cards.length; i++)
{
while (textScan.hasNextLine())
cards[i] = textScan.nextLine();
}
}
}
这是错误:
Card.java:7: error: unreported exception FileNotFoundException; must be caught or declared to be thrown
Scanner textScan = new Scanner(inputFile);
^
1 error
提前感谢,对于java来说我也很新,因为你可以从我的工作中得知,所以如果你能尽可能地愚蠢地回复你的回复,那将非常感激:)
答案 0 :(得分:0)
Constructor of Scanner
声明抛出FileNotFoundException
所以必须处理它(通过捕获或重新抛出)
答案 1 :(得分:0)
您必须使用像此一样的Try-Catch语句来捕获异常
try{
Scanner textScan = new Scanner(inputFile);
}catch(FileNotFoundException e) {
System.out.println("Error!");
}
如果找不到引用文件'inputFile',就像告诉Java要做什么。