【问题标题】:How do I get the list of numbers off of a file that the user inputs in Java?如何从用户在 Java 中输入的文件中获取数字列表?
【发布时间】:2014-05-26 14:11:45
【问题描述】:

我正在使用 Java eclipse,我想让用户输入文件名以从文件中检索分数列表。我的目标是取这些数字的平均值。我需要哪一行代码才能让用户输入文件名并让程序获取这些数字以便我可以使用它们进行计算?目前我可以让用户输入分数,但我需要从文件中获取数字。我访问了该站点上的许多资源。以下是一些:

BufferedReaderError finding fileGetting 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


【解决方案1】:

如果您想查找文件中数字的平均值,您可以执行以下操作:

// 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));

// Initialize our relevant counters
double sum = 0.0;
int numStudents = 0;

// While there is still stuff in the file...
while (fileToRead.hasNext()) { 
    // Is this next line consisting of just a number?
    if (fileToRead.hasNextDouble()) {
        // If it is, accumulate
        sum += fileToRead.nextDouble();
        numStudents++;
     } 
     else { // Else, just skip to the next line
         fileToRead.next();
     }   
}  
// Close the file when finished
fileToRead.close();

// Print the average:
System.out.println("The average mark is: " + (sum / numStudents));

此代码将创建一个新的Scanner 对象,该对象将从您的键盘读取输入。一旦这样做了,你输入文件名,它就可以通过打开另一个Scanner 对象来访问这个文件。之后,我们初始化一些计数器来帮助我们计算平均值。它们是sum,它将把我们遇到的所有分数加起来,numStudents,它跟踪文件中有多少学生。

while 循环将继续循环遍历该文件的每一行,直到到达末尾。重要的是您检查您接下来阅读的行是否包含单个数字 (double)。如果是,则将其添加到我们的总和中。如果不是,请跳到下一行。

完成后,关闭文件,然后在读取文件中的数字时将总和除以我们遇到的学生总数来显示平均值。

刚刚查看了您的个人资料和您的个人资料信息。你还有很长的路要走。祝你好运!

【讨论】:

  • 感谢您的帮助和理解@rayryeng :) 我尝试了上面的代码,但它无法找到有问题的文件。我也尝试使用此解决方案 (stackoverflow.com/questions/22973652/…),它得到了文件,但是,即使当我打开文件时,它也有很多不在文件中的文本(文本大小信息、文本样式等)文件看起来很正常,只列出了几个数字。我试过使用整个文件路径来定位文件以及“esp.txt”
  • 以上代码假定文件与调用程序的位置在同一位置。这可能就是它不起作用的原因,我可能应该在我的帖子中提出一个小警告。你能把我链接到这个文件在哪里吗?我想亲自看看。我的直觉是你读错了文件。
  • 我相信我将它与程序放在同一个位置。我希望这是您需要的信息.../Users/stephaniegross/Documents/workspace/Exam Statistics Program/src/Average
  • 哦,我终于通过下载 textwrangler (mac) 删除了所有出现的格式数据,并删除了使用 TextEdit 时我看不到的内容。
  • 我想查看实际文本文件本身的内容。如果这个程序应该可以工作,那么每一行应该只有一个数字
【解决方案2】:

查看有关扫描的 Java 教程:http://docs.oracle.com/javase/tutorial/essential/io/scanning.html,尤其是 ScanSum 示例。它展示了如何从文本文件中扫描双精度值并添加它们。您应该能够为您的项目修改此示例。

【讨论】:

    【解决方案3】:
    Scanner userInput = new Scanner(System.in);
    System.out.println("ENter filename");
    String fileName = userInput.next();
    Scanner fileScan = new Scanner(new File(fileName));
    

    然后使用扫描器方法来处理您感兴趣的行或字符串标记。

    【讨论】:

    • 谢谢@newbieee。我尝试了上面的代码,看看是否可以清除在我获得文件以导入数字后出现的一些不必要的文本,但它强调了“new Scanner(new File(fileName));”红色并告诉我我需要添加 throws 声明或用 try/catch 包围。我感到很困惑。我问我的教授我是否应该放弃课程并进行介绍,但他向我保证我会没事的......现在放弃为时已晚,我需要尽快学习所有这些:(
    猜你喜欢
    • 2011-06-07
    • 2011-07-14
    • 2016-06-18
    • 2022-11-24
    • 1970-01-01
    • 2012-01-29
    相关资源
    最近更新 更多