【问题标题】:Java program - Reading numeric data from txt fileJava 程序 - 从 txt 文件中读取数值数据
【发布时间】:2015-03-04 21:49:51
【问题描述】:

此 Java 程序用于从包含多个整数的 txt 文件中查找数据。我已经找出了运行程序的最大值、平均值的代码。对于很多人来说,这应该很简单,但我在编程方面相对缺乏经验,所以请耐心等待。


我遇到问题的三个代码如下。

  1. 高于平均水平的数字数量
  2. 素数个数
  3. 求总和

有谁知道这样做的方法吗? 谢谢。任何建议都会有所帮助。


这是20个数字的txt文件示例

  1. 1
  2. 12
  3. 34
  4. 54
  5. 36
  6. 76
  7. 67
  8. 86
  9. 45
  10. 44
  11. 33
  12. 22
  13. 2
  14. 4
  15. 7
  16. 87
  17. 89
  18. 99
  19. 432
  20. 543

列表项

package Assignment1;

import java.io.File;
import java.io.IOException;
import java.util.Scanner;

public class Assignment1 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        // Define two arrays - local variables
        // Declaring 10 integers
        int[] myIntArray = new int[20];
        // Declaring 10 strings

        //File
        File f = new File ("inputassignment1.txt");

        try {
            Scanner sc = new Scanner(f);    //Scanner
             for (int i=0; i < myIntArray.length; i++) {
                 myIntArray[i] = sc.nextInt();
            }
            // Closing the file
            sc.close();

       } catch (IOException e) {
            System.out.println("Unable to create : "+e.getMessage());      
       }

        System.out.println("Highest number: " + maxNum(myIntArray));

        System.out.println("Average number: "+aveNum(myIntArray));
//      System.out.println(allNum(myIntArray));
    //  System.out.println(avgPlus(myIntArray));
    }// end of main

【问题讨论】:

  • 到目前为止你尝试过什么?我看到您正在阅读数字,但到目前为止您还没有尝试对它们做任何事情。
  • 您问“有人知道这样做的方法吗?”在回答是的,我知道很多方法。但是你尝试了什么,你坚持什么
  • 我算出最大数是: public static int maxum(int[] MaxNum) { int Max = 0; for (int i = 0; i Max) { Max = MaxNum[i]; } } 返回最大值; }
  • 已编辑问题:删除了请求代码。来吧,这些都没有。你已经有答案了,好好努力吧。如果您不理解答案,请通过评论他们的答案来要求他们澄清。另外,请避免在 cmets 中发布代码,因为它不会正确格式化并且不会得到应有的关注。如果您需要向我们展示新代码(但不要要求其他人为您提供代码),请编辑您的问题。
  • 对不起,小伙子们,我一开始并不清楚,正如我之前在描述中提到的那样。我在编程方面经验不是很好,尤其是在 Java 方面。

标签: java arrays algorithm text-files


【解决方案1】:

让我们分解你的任务:

总共有 3 个任务:

  1. 计算有多少数字高于平均水平
  2. 求总和
  3. 找出所有质数

每一项都要求您:

  • 从文本文件中读入数字(可能读入数组)
  • 对它们执行一些检查(例如if isPrime(number) { primes[numPrimes] = number; numPrimes++; }
  • 数一数有多少(numNumbers++,每个数字)
  • 总结它们(totalSum += number,每个数字)

对于第一个循环,您需要在获得计数/总和后添加另一个循环,另外两个应该可以通过修改第一个循环来实现(我在下面展示了一个示例)。

我认为您应该能够在谷歌上搜索如何执行这些操作。上面的代码看起来是一个很好的起点。

int numNumbers = 0;
int totalSum = 0;
for (int i=0; i < myIntArray.length; i++) {
    myIntArray[i] = sc.nextInt();
    numNumbers++;
    totalSum += myIntArray[i];
}

【讨论】:

    猜你喜欢
    • 2012-01-13
    • 2016-05-27
    • 1970-01-01
    • 2018-11-01
    • 1970-01-01
    • 2012-02-08
    • 2023-03-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多