【发布时间】:2014-05-26 14:11:45
【问题描述】:
我正在使用 Java eclipse,我想让用户输入文件名以从文件中检索分数列表。我的目标是取这些数字的平均值。我需要哪一行代码才能让用户输入文件名并让程序获取这些数字以便我可以使用它们进行计算?目前我可以让用户输入分数,但我需要从文件中获取数字。我访问了该站点上的许多资源。以下是一些:
BufferedReader、Error finding file、Getting a list from a file
package Average;
/**An average of scores*/
import java.util.Scanner;
public class Average2 {
public static void main(String[] args) {
int grade = 0;
int students = 0;
float total = 0;
double average = 0;
Scanner input = new Scanner(System.in);
System.out.println("Enter number of students: ");
students = input.nextInt();
if (students <= 10) {
System.out.println("Enter the grades of the students: ");
for(int i = 0; i < students; i++) {
do {
grade = input.nextInt();
} while(grade < 0 || grade > 100);
total += grade;
}
average = (total/students);
int median = ((82+84)/2);
System.out.println("The average is " + average);
System.out.println("The mean is " + median);
}
}
}
更新自上述帖子!
package trials;
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class trials2 {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
// Create new Scanner object to read from the keyboard
Scanner in = new Scanner(System.in);
// Grab the name of the file
System.out.println("Enter filename: ");
String fileName = in.next();
// Access the file
Scanner fileToRead = new Scanner(new File(fileName));
// While there is still stuff in the file...
double sum = 0;
while (fileToRead.hasNext()) {
if (fileToRead.hasNextDouble()) {
sum += fileToRead.nextDouble();
} else {
fileToRead.next();
}
}
{
fileToRead.close();
}
System.out.println(sum);
}
}
我从中得到的结果:
输入文件名:
esp.txt
501.0
【问题讨论】:
-
他们会在哪里输入?进入控制台?
-
这看起来像家庭作业..
-
我对 Java 完全陌生。我现在正在网上学习这门课程,但没有任何背景知识:-/我试过这个代码:Scanner in = new Scanner(System.in); System.out.println("文件名是什么?");字符串输入 = in.nextLine();这允许我获取用户输入,但我不知道如何让它从那里读取它。
-
while (in.hasNext()) { System.out.println (in.next()); }
-
你需要设置另一个计数器来计算你读了多少次一个数字。完成后,将总和除以这个数字。在
double sum = 0;之后,放置int numStudents = 0;在if (filetoRead...)语句中,放置numStudents++;。最后,你最后的System.out.println()声明,这样做:System.out.println(sum/numStudents);
标签: java input filenames average