簡體   English   中英

程序無法從.txt文件讀取

[英]Program not reading from .txt file

我正在嘗試從名為input的txt文件中讀取三個變量。當我運行程序時,txt包含12 33.44和Peter,這些變量不會輸出

package lab9;
import java.util.Scanner;              // Needed to use Scanner for input
import java.io.File;                   // Needed to use File
import java.io.FileNotFoundException;  // Needed for file operation

public class FileScanner 
{ 
   public static void main(String[] args) 
  // Needed for file operation 
         throws FileNotFoundException 
   {  

// Declare the int variable
       int a=0;
 //Declare the floating point number
       double b=0;
 //Declare the string variable
       String s=null;
 //Declare a variable to hold the sum
       double sum =0;
// Create a file object that takes "input.txt" as input
       File oInput= new File("input.txt") ;
// Setup a Scanner to read from the text file that you created
       Scanner gilz=new Scanner(oInput);

// use nextInt() to read the integer
       while (gilz.hasNextInt())
       {
         a = gilz.nextInt();
       }
         System.out.println ("the integer read is " + a);

// use nextDouble() to read double
     while(gilz.hasNextDouble())
     {
         b = gilz.nextDouble();
     }
         System.out.println ("the floating point number read is "+ b);

// use next() to read String
       while(gilz.hasNextLine())
       {
       s = gilz.nextLine();
       }
         System.out.println ("the string read is "+ s);
       while((gilz.hasNextDouble())&&(gilz.hasNextInt()))
       {
           sum = a + b;
       }
           System.out.println("HI! "+s +", the sum of "+a+"and "+b+" is "+sum);
    }
}

當我嘗試運行該程序時,沒有任何輸出,屏幕上也沒有打印任何變量,如何使用.nextInt()或.next()方法使掃描儀從txt文件讀取?

使用您將閱讀的文件的完整路徑。 我使用的是使用FileReader和BufferedReader的示例,您將需要使用new File("c:\\\\input.txt)

看下面的例子:

public static void main(String[] args) {

    BufferedReader br = null;

    try {

        String sCurrentLine;

        br = new BufferedReader(new FileReader("C:\\input.txt"));

        while ((sCurrentLine = br.readLine()) != null) {
            System.out.println(sCurrentLine);
        }

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (br != null)br.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

}

暫無
暫無

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

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