简体   繁体   中英

Program not reading from .txt file

I am trying to read three variables from a txt file called input input.txt contains 12 33.44 and Peter when I run the program these variables are not outputted

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);
    }
}

when I try to run the program I get no output , no variables are printed on the screen how do I get my scanner to read from the txt file using .nextInt() or .next() methods ?

Use the complete path of the file that you'll read. I am using an example using FileReader and BufferedReader, you'll need to do the same using new File("c:\\\\input.txt) .

Look at the example below:

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();
        }
    }

}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM