为什么运行时数组“freq”中的所有数字都显示为0?我试图使它们成为1到9之间的数字。最后,最后一个for循环应该选出最常出现的数组中的数字。我很坚持这个:(
import java.util.*;
public class MostFrequent {
public static void main(String[] args) {
int[] freq = new int[10]; //creat an array
for (int i = 0; i < args.length; i++){
int element;
try {
element = Integer.parseInt(args[i]); // turns each element into an integer
} catch (NumberFormatException e){
continue; // ignores all non integers
}
if (element >= 0 && element <= 9){
freq[element] += 1; // ensures only signle digit #s
}
}
System.out.println(Arrays.toString(freq));
int max = 0;
for (int i = 0; i < freq.length; i++){
if (freq[i] > max){
max = freq[i];
}
}
//prints the number that appears most frequently
for (int i = 0; i < freq.length; i++){
if (freq[i] == max){
System.out.println("The digit that appears most frequently is " + i);
}
}
}
}
答案 0 :(得分:4)
您需要将输入作为命令行参数传递给程序,而不会使其无法正常工作
喜欢
java MostFrequent 1 2 3 4 5 6 7 8 9
因为 args 包含通过命令行传递给程序的参数
如果你正在使用eclipse goto run&gt; arguments&gt;程序参数输入1 2 3 4 5 6 7 8 9那里
答案 1 :(得分:1)
如果在运行程序时没有向程序传递任何参数,则只需要一个空的int[]
数组,因为设置值的频率的循环永远不会运行(args.length
将为0)。 int
默认为0。
答案 2 :(得分:1)
我建议您使用扫描程序(而不是args
中的命令行参数)。因此,您输入freq.length
位数,然后停止。像这样 -
public static void main(String[] args) {
int[] freq = new int[10]; // create an array
Scanner scanner = new Scanner(System.in);
for (int i = 0; i < freq.length; i++) {
int element = scanner.nextInt(); // turns each
// element into
// an integer
if (element >= 0 && element <= 9) {
freq[element] += 1; // ensures only single digit #s
} else {
i = (i < 1) ? 0 : i - 1;
}
}
scanner.close();
System.out.println(Arrays.toString(freq));
int max = 0;
for (int i = 0; i < freq.length; i++) {
if (freq[i] > max) {
max = freq[i];
}
}
// prints the number that appears most frequently
for (int i = 0; i < freq.length; i++) {
if (freq[i] == max) {
System.out.println("The digit that appears most frequently is "
+ i);
}
}
}