JAVA从文本文件中读取整数并在Arraylists上工作

时间:2011-06-09 14:35:06

标签: java arrays parsing file

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

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

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

感谢 aioobe first part提供了很好的答案。

现在我想以这种方式开发它:

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

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

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

  4. 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
    
    
    }
    

3 个答案:

答案 0 :(得分:0)

您传递的是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!"); 
            }



P.S.这与你的问题无关,但是有一个强大的java约定,类名以大写字母开头。

答案 1 :(得分:0)

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

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


}

答案 2 :(得分:-1)

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