JAVA 读取整数形成文本文件并处理数组列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6294541/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JAVA Read Integers form a Text File and Work on the Array Lists
提问by Mehdi
I have a text file containing the following content:
我有一个包含以下内容的文本文件:
0 12
1 15
2 6
3 4
4 3
5 6
6 12
7 8
8 8
9 9
10 13
I want to read these integers from a txt file and save the two columns into two different arrays in Java.
我想从 txt 文件中读取这些整数,并将两列保存到 Java 中的两个不同数组中。
Thanks to aioobefor his nice answer for the first part.
感谢aioobe对第一部分的精彩回答。
Now I want to develop it in this way:
现在我想以这种方式开发它:
Write a method called
occurrence
, that take a number as an input and write the number of occurrence that this number has.Write another method called
occurrences
, that didn't have any input, but as output it gives the number that has the major number of occurrences (in the second column) in the file.At last, the
Main
program will ask the user to write a number from 1 to 3.
编写一个名为 的方法
occurrence
,该方法将一个数字作为输入并写出该数字出现的次数。编写另一个名为 的方法
occurrences
,它没有任何输入,但作为输出,它给出了文件中出现的主要次数(在第二列中)的数字。最后,
Main
程序会要求用户写一个从 1 到 3 的数字。
1=method that, from an input number (that is the number in the first column) gives back the associated number in the second column.
1=方法,从输入数字(即第一列中的数字)返回第二列中的关联数字。
2=the first occurrence method (the one with input)
2=第一个出现的方法(有输入的那个)
3=the second occurrence method (the one without input)
3=第二种出现方式(没有输入的那种)
I wrote the code but there is some errors(about passing the array list to a method) and I need your help about that. I am a JAVA novice, So if you feel that the code is not appropriate, please make the required changes. This is my final code:
我写了代码,但有一些错误(关于将数组列表传递给方法),我需要你的帮助。我是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
}
回答by amit
you are passing an Object[]
while your method expects an int[]
(note that toArray() returns an Object[])
also, occurrence()
is an instance method, while main is static, you will need to change occurrence()
to be a static method as well, or create an instance of list.
so methods signature will be:
您正在传递一个Object[]
while 您的方法需要一个int[]
(注意 toArray() 返回一个 Object[])
也是occurrence()
一个实例方法,而 main 是静态的,您也需要更改occurrence()
为静态方法,或创建一个实例的名单。
所以方法签名将是:
public static void occurrences(Integer[] arg)
public static void occurrence(Integer[] arg)
and methods calls will be:
和方法调用将是:
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. this is not related to your question, but there is a strong java convention that a class name starts with a capital letter.
ps 这与您的问题无关,但是有一个强大的 Java 约定,即类名以大写字母开头。
回答by Mehdi
This is the final answer(I also updated the methods):
这是最终答案(我也更新了方法):
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
}
回答by user219882
I would prefer BufferedReader. Read it line by line and use String.split() method to get the column elements.
我更喜欢BufferedReader。逐行读取并使用 String.split() 方法获取列元素。