【问题标题】:JAVA Read Integers form a Text File and Work on the Array ListsJAVA 从文本文件中读取整数并处理 Arraylists
【发布时间】:2011-06-09 14:35:06
【问题描述】:

我有一个包含以下内容的文本文件:

0 12
1 15
2 6
3 4
4 3
5 6
6 12
7 8
8 8
9 9
10 13

我想从一个 txt 文件中读取这些整数并将这两列保存到 Java 中的两个不同数组中。

感谢 aioobefirst part 的精彩回答。

现在我想这样开发:

  1. 编写一个名为occurrence 的方法,该方法将一个数字作为输入并写入该数字出现的次数。

  2. 编写另一个名为 occurrences 的方法,它没有任何输入,但作为输出,它给出了文件中出现次数最多的数字(在第二列中)。

  3. 最后,Main 程序会要求用户写一个从 1 到 3 的数字。

1= 方法,从输入数字(即第一列中的数字)返回第二列中的关联数字。

2=第一种出现方式(带输入的方式)

3=第二种出现方式(无输入)

我编写了代码,但有一些错误(关于将数组列表传递给方法),我需要您的帮助。 我是一个JAVA新手,所以如果你觉得代码不合适,请进行必要的修改。 这是我的最终代码:

import java.util.*; //importing some java classes
import java.lang.*;
import java.io.*;

public class list {

    public static void main(String[] args) {

        // Read the text file and store them into two arrays:
        try {
            List<Integer> column1 = new ArrayList<Integer>();   // Defining an integer Array List
            List<Integer> column2 = new ArrayList<Integer>();   // Defining an integer Array List

            Scanner myfile = new Scanner(new FileReader("c:/java/data.txt")); // Reading file using Scanner

            while (myfile.hasNext()) {          // Read file content using a while loop
                column1.add(myfile.nextInt());      // Store the first integer into the first array list
                column2.add(myfile.nextInt());      // Store the next integer into the second array list
            }

            myfile.close(); // close the file

            System.out.println("column 1 elements are:\n" + column1);  // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
            System.out.println("column 2 elements are:\n" + column2);  // [12, 15, 6, 4, 3, 6, 12, 8, 8, 9, 13]

            //Getting a number(1-3) from user:
            Scanner cases = new Scanner(System.in);
            System.out.println("Enter a number between 1-3: "); 
            int num = cases.nextInt();

            switch (num) {
                case 1:
                    Scanner case1 = new Scanner(System.in);
                    System.out.println("Enter a number from first column to see how many occurrences it has: "); 
                    int numb = case1.nextInt();
                    System.out.println(column2.get(numb));
                    break;
                case 2:
                    occurrence(column2.toArray());
                    break;
                case 3:
                    occurrences(column2.toArray());
                    break;              
                default: System.out.println("the number is not 1 or 2 or 3!"); 
            }

        } catch (Exception e) {     // we defined it just in the case of error
            e.printStackTrace();    // shows the error
        }

    } // End of MAIN


    public void occurrence(int[] arg) { // Defining occurrence method

        int count = 0;

        //Getting a number from user input:
        Scanner userin = new Scanner(System.in);
        System.out.println("Enter an integer number: "); 
        int number = userin.nextInt();        

        // Finding the occurrences:
        for (int i = 0; i < arg.length; i++)
            if (arg[i] == number) count++;

        System.out.println( number + " is repeated " + count + " times in the second column.");
    } // End of occurrence method


    public void occurrences(int[] arg) {    // Defining occurrenceS method

        int max = 0;

        // Finding the maximum occurrences:
        for (int i = 1; i < arg.length; i++)
            if (arg[i] > arg[max]) max = i;
            System.out.println( max + " is the most repeated  number." );
    } // End of occurrenceS method


}

【问题讨论】:

    标签: java arrays parsing file


    【解决方案1】:

    您正在传递一个Object[],而您的方法需要一个int[]
    (注意 toArray() 返回一个 Object[])
    另外,occurrence() 是一个实例方法,而 main 是静态方法,您需要将 occurrence() 也更改为静态方法,或者创建一个列表实例。
    所以方法签名将是:

    public static void occurrences(Integer[] arg) 
    
    public static void occurrence(Integer[] arg)
    

    方法调用将是:

    Integer[] temp = new Integer[column2.size()];
                switch (num) {
                    case 1:
                        Scanner case1 = new Scanner(System.in);
                        System.out.println("Enter a number from first column to see how many occurrences it has: "); 
                        int numb = case1.nextInt();
                        System.out.println(column2.get(numb));
                        break;
                    case 2:
                        occurrence(column2.toArray(temp));
                        break;
                    case 3:
                        occurrences(column2.toArray(temp));
                        break;              
                    default: System.out.println("the number is not 1 or 2 or 3!"); 
                }
    



    附言。这与您的问题无关,但是有一个强大的 Java 约定,即类名以大写字母开头。

    【讨论】:

      【解决方案2】:

      这是最终答案(我也更新了方法):

      import java.util.*; //By Mehdi Davoudi
      import java.lang.*;
      import java.io.*;
      
      public class list {
      
          public static void main(String[] args) {
      
              // Read the text file and store them into two arrays:
              try {
                  List<Integer> column1 = new ArrayList<Integer>();   // Defining an integer Array List
                  List<Integer> column2 = new ArrayList<Integer>();   // Defining an integer Array List
      
                  Scanner myfile = new Scanner(new FileReader("c:/java/data.txt")); // Reading file using Scanner
      
                  while (myfile.hasNext()) {          // Read file content using a while loop
                      column1.add(myfile.nextInt());      // Store the first integer into the first array list
                      column2.add(myfile.nextInt());      // Store the next integer into the second array list
                  }
      
                  myfile.close(); // close the file
      
                  System.out.println("column 1 elements are:\n" + column1);  // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
                  System.out.println("column 2 elements are:\n" + column2);  // [12, 15, 6, 4, 3, 6, 12, 8, 8, 9, 13]
      
                  //Getting a number(1-3) from user:
                  Scanner cases = new Scanner(System.in);
                  System.out.println("Enter a number between 1-3: "); 
                  int num = cases.nextInt();
      
                  Integer[] temp = new Integer[column2.size()];
      
                  switch (num) {
                      case 1:
                          Scanner case1 = new Scanner(System.in);
                          System.out.println("Enter a number from first column to see its pair in second column: "); 
                          int numb = case1.nextInt();
                          System.out.println(column2.get(numb));
                          break;
                      case 2:
                          Occurrence(column2.toArray(temp));
                          break;
                      case 3:
                          Occurrences(column2.toArray(temp));
                          break;              
                      default: System.out.println("the number is not 1 or 2 or 3!"); 
                  }
      
      
              } catch (Exception e) {     // we defined it just in the case of error
                  e.printStackTrace();    // shows the error
              }
      
          } // End of MAIN
      
      
          public static void Occurrence(Integer[] arg) {  // Defining occurrence method
      
              int count = 0;
      
              //Getting a number from user input:
              Scanner userin = new Scanner(System.in);
              System.out.println("Enter an integer number: "); 
              int number = userin.nextInt();        
      
              // Finding the occurrences:
              for (int i = 0; i < arg.length; i++)
                  if (arg[i] == number) count++;
      
              System.out.println( number + " is repeated " + count + " times in the second column.");
          } // End of occurrence method
      
      
          public static void Occurrences(Integer[] ary) { // Defining occurrenceS method
              // Finding the maximum occurrences:
              Map<Integer, Integer> m = new HashMap<Integer, Integer>();
      
              for (int a : ary) {
                  Integer freq = m.get(a);
                  m.put(a, (freq == null) ? 1 : freq + 1);
              }
      
              int max = -1;
              int mostFrequent = -1;
      
              for (Map.Entry<Integer, Integer> e : m.entrySet()) {
                  if (e.getValue() > max) {
                      mostFrequent = e.getKey();
                      max = e.getValue();
                  }
              }
      
              System.out.println( mostFrequent + " is the most repeated  number in second column." );
          } // End of occurrenceS method
      
      
      }
      

      【讨论】:

        【解决方案3】:

        我更喜欢BufferedReader。逐行读取,使用 String.split() 方法获取列元素。

        【讨论】:

        • 这与他的问题没有任何关系。他的文件处理没有问题。
        猜你喜欢
        • 1970-01-01
        • 2018-07-22
        • 1970-01-01
        • 1970-01-01
        • 2017-11-14
        • 1970-01-01
        • 2017-03-29
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多