【发布时间】: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 中的两个不同数组中。
感谢 aioobe 对first part 的精彩回答。
现在我想这样开发:
编写一个名为
occurrence的方法,该方法将一个数字作为输入并写入该数字出现的次数。-
编写另一个名为
occurrences的方法,它没有任何输入,但作为输出,它给出了文件中出现次数最多的数字(在第二列中)。 最后,
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
}
【问题讨论】: