[英]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 我正在尝试从名为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);
}
}
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 ? 当我尝试运行该程序时,没有任何输出,屏幕上也没有打印任何变量,如何使用.nextInt()或.next()方法使扫描仪从txt文件读取?
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)
. 我使用的是使用FileReader和BufferedReader的示例,您将需要使用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();
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.