我正在尝试让用户输入一个整数,基于整数值,我正在调用mix函数来读取文件内容,如下面的代码所示。我收到了,这个错误:
Project2.java:43: variable urlScan might not have been initialized
while (urlScan.hasNext())
^
Project2.java:34: unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown
fileScan = new Scanner (new File("input.txt"));
^
任何想法,我在这里可能做错了什么?
import java.util.Scanner;
import java.io.*;
public class Project2
{
public static void main(String[] args)
{
System.out.println("Select an item from below: \n");
System.out.println("(1) Mix");
System.out.println("(2) Solve");
System.out.println("(3) Quit");
int input;
Scanner scan= new Scanner(System.in);
input = scan.nextInt();
System.out.println(input);
if(input==1) {
mix();
}
else{
System.out.println("this is exit");
}
}
public static void mix()
{
String url;
Scanner fileScan, urlScan;
fileScan = new Scanner (new File("input.txt"));
// Read and process each line of the file
while (fileScan.hasNext())
{
url = fileScan.nextLine();
System.out.println ("URL: " + url);
//urlScan = new Scanner (url);
//urlScan.useDelimiter("/");
// Print each part of the url
while (urlScan.hasNext())
System.out.println (" " + urlScan.next());
System.out.println();
}
}
}
答案 0 :(得分:3)
错误很有表现力。
urlScan
本地变量(本地变量未获取默认值)fileScan = new Scanner (new File("input.txt"));
换成try/catch
。或者声明您的方法可能会在方法签名中抛出FileNotFoundException。 (新文件(str)可能会抛出FileNotFoundException
这是已检查的异常,编译器会强制您处理它。)答案 1 :(得分:1)
首先,urlScan
未初始化。
其次,您应该使用fileScan = new Scanner (new File("input.txt"));
的try / catch包围FileNotFoundException
。
答案 2 :(得分:1)
本地变量必须才能在使用前进行初始化,因此请取消注释此行:
urlScan = new Scanner (url);