I am trying to have user input an interger, based on the integer value, I am calling mix function to read in the file contents as code shows below. I am getting, this error:
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"));
^
Any ideas, what I might be doing wrong here?
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();
}
}
}
The errors are pretty expressive.
urlScan
local variable (local variables don't get default values) fileScan = new Scanner (new File("input.txt"));
around try/catch
. or declare that your method might throw FileNotFoundException in your method signature. (new File(str) might throw FileNotFoundException
which is a checked exception and compiler will force your handled it). First, urlScan
isn't initialized.
Second, you should surround fileScan = new Scanner (new File("input.txt"));
with an try/catch for FileNotFoundException
.
局部变量必须在使用前进行初始化,因此请取消注释此行:
urlScan = new Scanner (url);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.