1

我正在尝试计算模式的数量,并将模式作为输出,但我遇到了一些困难。你能帮帮我吗?

public class Main{
    public static void main(String[] args){

        int modes;
        int terval = -1;
        int[]a;

        while(a != terval){                     //problem is in this line and after.
            a = IO.readInt[];              

            for(int i = 0; i < a.length; i++){
                int count = 0;
                for(int j = 0;j < a.length; j++){
                    if(a[j] == a[i])
                        count++;        
                }
                modes = a[i];
            }
        }
        System.out.println(count);
        System.out.println(modes);
    }
}
4

1 回答 1

2

This line: while(a != terval) contains a compilation error.

  1. int[] a was never initialized so it has a null a value when the loop begins.

  2. int[] a is an integer array and int terval is an integer. The conditional a != terval is undefined because you cannot compare an int array to an int.

Undefined Comparison: int[] != int

You can compare a single integer in the integer array to another single integer

Defined Comparison: int[x] != int

This would work: a[x] != terval where x is an array index you want to check

Consider this revision:

public class Main{
public static void main(String[] args){

boolean go = true; //controls master loop
int modes;
int terval = -1;
int[]a;

while(go) { //master loop
    a = IO.readInt[];              
    for(int i = 0; i < a.length; i++){
      go &= !(a[i] == -1); //sets go to false whenever a -1 is found in array
                           //but the for loops do not stop until 
                           //the array is iterated over twice
      int count = 0;
      for(int j = 0;j < a.length; j++){
        if(a[j] == a[i])
            count++;        
      }
      modes = a[i];         
    }
}
System.out.println(count);
System.out.println(modes);

}

To get user input from the Console:

import java.util.Scanner;
public class Main{

  public static void main(String[] args){

    Scanner in = new Scanner(System.in);
    boolean go = true;
    int modes;
    int count;
    int size = 32; //max array size of 32
    int terval = -1;
    int t=0;
    int i=0;
    int[] a = new int[size]; 

    while(go && i < size) { //master loop
      t = in.nextInt();
      go &= !(t == terval);
      if (go) { a[i++] = t; }  
    }
    // "a" is now filled with values the user entered from the console
    // do something with "modes" and "count" down here
    // note that "i" conveniently equals the number of items in the partially filled array "a"
  }
}
于 2012-11-18T21:35:17.770 回答