Java 程序未从.txt文件读取

Java 程序未从.txt文件读取,java,Java,我试图从一个名为input的txt文件中读取三个变量 input.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.FileNotFoundExce

我试图从一个名为input的txt文件中读取三个变量 input.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的示例,您需要使用新的
文件(“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();
        }
    }

}

是否正在输出任何错误?是否可以捕获
FileNotFound
异常并打印堆栈跟踪?只需尝试该代码,它就会输出变量。除了总和始终为0,因为文件中没有更多的数字,为什么您认为
BufferedReader(FileReader))
Scanner(File)更好
?它解决了什么问题?你可以在这里看到答案:我没有问这两种方法之间有什么区别。我问你为什么认为这里应该使用
BufferedReader(文件阅读器)
,而不是
Scanner(文件)
?它是如何解决OP问题的?一旦扫描器有了更多的读取方法,bufferedreader就会比扫描器更快…正因为如此,当然是“线程安全”的。好吧,但它是如何解决OP问题的?请注意,这不是一个有效的答案,但评论说这个问题需要更多关于实际问题的细节。