2 回答
TA贡献1824条经验 获得超8个赞
把这些线getAverage()只是以前生产while循环,让你开始一个新的Scanner读取文件的内容:
File file = new File(fileNameReading1);
Scanner in = null;
try {
in = new Scanner(file);
} catch (FileNotFoundException e) {
System.out.println("File not found");
e.printStackTrace();
return;
}
编辑,这一行:
in = new Scanner(file);
构造一个新的 Scanner,它生成从指定文件扫描的值。
(来自 Scanner.java)
因此inScanner 对象将用于获取文件的行。
TA贡献1852条经验 获得超7个赞
这应该工作
package org.test;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
public class readFile {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter the File Name: ");
String fileNameReading = in.next();
in.close();
try {
getAverage(fileNameReading);
} catch (IOException e) {
e.printStackTrace();
}
}
private static void getAverage(String fileNameReading) throws IOException {
FileInputStream fis;
try {
fis = new FileInputStream(fileNameReading);
InputStreamReader input = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(input);
String data;
double avg = 0;
String[] doublearray = null;
while ((data = br.readLine()) != null) {
doublearray = data.split(" "); // assuming the file contains only one line like x y , x and y are doubles
}
if(doublearray!= null && doublearray.length>0){
avg = (Double.parseDouble(doublearray[0])+Double.parseDouble(doublearray[1]))/2;
}
System.out.println("The Average of Double values is : "+avg);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
添加回答
举报