gpt4 book ai didi

java - 无法读取java中的文件

转载 作者:行者123 更新时间:2023-12-01 17:25:32 26 4
gpt4 key购买 nike

我试图让用户输入一个整数,基于整数值,我调用 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();
}
}
}

最佳答案

这些错误非常具有表现力。

  • 初始化 urlScan 局部变量(局部变量没有默认值)
  • fileScan = new Scanner (new File("input.txt")); 包裹在 try/catch 周围。或者声明您的方法可能会在方法签名中抛出 FileNotFoundException。 (new File(str) 可能会抛出 FileNotFoundException,这是一个检查异常,编译器将强制您处理它)。

关于java - 无法读取java中的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15191966/

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