[英]Trouble Reading numbers from a .txt file and arranging them into A-F grading, as well as finding max, min, and average numbers
I'm a little stuck on actually getting the scanner to open the file I have and arrange the numbers. 我有点想让扫描仪打开我拥有的文件并排列编号。 The computer tells me it recognizes the file I ask it to open, but then doesn't display the numbers.
计算机告诉我,它识别出我要求打开的文件,但是没有显示数字。 Any help would be greatly appreciated, thank you very much!
任何帮助将不胜感激,非常感谢!
package helloworld;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class textToArray {
public static void main(String[] args) throws FileNotFoundException{
//Open the file
File f = new File(" ");
System.out.println("Welcome to the Exam Statistics Program!");
Scanner scanner = new Scanner( System.in );
System.out.println("Please enter the name of the file: ");
String input = scanner.nextLine();
//Create a new scanner to read the file
Scanner s = new Scanner(input);
//Declare an array with length of 100
int[] array = new int[100];
int i = 0, min, max, sum = 0;
//Loop through the file if there is a next int to process it will continue
for(i = 0; s.hasNextInt(); i++){
//We store every int we read in the array
array[i] = s.nextInt();
}
//Close the scanner object
s.close();
//As the for loop will stop when there is no new int to read so the i++ will stop at the number of int in the file
//We use this number to calculate the average
int nbInArray = i;
//initialize min and max to the first array value which is for now empty
min = max = array[0];
for(int j = 0; j<nbInArray ; j++){
//Now we test if the new value if bigger than the initial value (0 or empty) the new value will become the max
if (array[j]>max){
max = array[j];
}
//Otherwise if the the value is smaller than the initial value the new value will become the minimum
//And so on every time we test if we have a smaller value the new one will become the min
if (array[j]<min){
min = array[j];
}
//The sum was initialised to 0 so we add every new int to it
sum = sum + array[j];
}
//We compute the avg , i declared it double in case we have decimal results
//double avg = sum / nbInArray;
//finally we print out the min, max and the average
System.out.println("The minimum is: "+min);
System.out.println("The maximum is: "+max);
//System.out.println("The averange is: "+avg);
}
}
You almost got it! 你差点知道了! Change this line:
更改此行:
Scanner s = new Scanner(input);
to: 至:
Scanner s = new Scanner(new File(input));
Hello you have to change some lines on your code: 您好,您必须在代码上更改一些行:
File f = new File(input);
//Create a new scanner to read the file
Scanner s = new Scanner(f);
You can also check that the user give you an existing file by using 您还可以使用以下命令检查用户是否向您提供了现有文件
f.exists();
last advice a class name should start with a capital letter. 最后的建议是,班级名称应以大写字母开头。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.