簡體   English   中英

無法讀取Java中的文件

[英]unable to read file in java

我試圖讓用戶輸入一個整數,基於整數值,我正在調用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。 (新的File(str)可能會拋出FileNotFoundException ,這是一個已檢查的異常 ,編譯器將強制您對其進行處理)。

首先, urlScan未初始化。

其次,您應該將fileScan = new Scanner (new File("input.txt")); 嘗試/捕獲FileNotFoundException

局部變量必須在使用前進行初始化,因此請取消注釋此行:

urlScan = new Scanner (url);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM