Java 使用方法进行文件I/O
在我的程序中,使用扫描仪获取用户输入的文件名。用户在控制台中输入.txt文件名,我也在控制台中获得了输出,但现在如果我想使用此方法执行此程序:Java 使用方法进行文件I/O,java,loops,methods,file-io,Java,Loops,Methods,File Io,在我的程序中,使用扫描仪获取用户输入的文件名。用户在控制台中输入.txt文件名,我也在控制台中获得了输出,但现在如果我想使用此方法执行此程序: public static double deviation(File inputFile) 我如何实施我的计划 public static void main(String[] args) throws FileNotFoundException { // TODO Auto-generated method stub
public static double deviation(File inputFile)
我如何实施我的计划
public static void main(String[] args) throws FileNotFoundException {
// TODO Auto-generated method stub
double number = 0;
double n = 0;
double sum = 0;
double sum1 = 0;
int count = 0;
double mean = 0;
Scanner Scanscan = new Scanner(System.in);
System.out.print("Enter the name of the file: ");
String filename = Scanscan.nextLine();
File inputFile = new File(filename);
Scanner reader = new Scanner(inputFile);
while(reader.hasNext()){
number = reader.nextDouble();
sum = sum + number;
sum1 = sum1 + Math.pow(number,2);
n++;
}
double n1 = Math.sqrt(n);
double sum11 = Math.sqrt(sum1);
mean = sum / n;
double n12 = Math.pow(n,2) - n;
double n22 = Math.pow(sum, 2);
double x = ( n * sum1 - n22) / (n12);
double deviation = (Math.sqrt(x));
System.out.println( "The standard deviation of the values in this file is: " + deviation);
}
通过将必要的部分移动到新方法中
public static double deviation(File inputFile){
double number = 0;
double n = 0;
double sum = 0;
double sum1 = 0;
int count = 0;
double mean = 0;
Scanner reader = new Scanner(inputFile);
while(reader.hasNext()){
number = reader.nextDouble();
sum = sum + number;
sum1 = sum1 + Math.pow(number,2);
n++;
}
double n1 = Math.sqrt(n);
double sum11 = Math.sqrt(sum1);
mean = sum / n;
double n12 = Math.pow(n,2) - n;
double n22 = Math.pow(sum, 2);
double x = ( n * sum1 - n22) / (n12);
return Math.sqrt(x);
}
public static void main(String[] args) throws FileNotFoundException {
Scanner Scanscan = new Scanner(System.in);
System.out.print("Enter the name of the file: ");
String filename = Scanscan.nextLine();
File inputFile = new File(filename);
double deviation = deviation(inputFile);
System.out.println( "The standard deviation of the values in this file is: " + deviation);
}
现在还不清楚你在问什么——你是说“我如何将代码重构成一个方法?”