2012-11-18 120 views
1

我想获取模式的计数,并将模式输出为输出 但我遇到了一些困难。你能帮我吗?java,打印输出模式

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); 
    } 
} 
+0

程序结束-1。 – javaisjusttoohard

回答

2

这行:while(a != terval)包含编译错误。

  1. int[] a从未初始化,所以它有一个null值循环开始时。

  2. int[] a是一个整数数组而int terval是一个整数。条件a != terval未定义,因为您无法将int数组与int进行比较。

未定义比较:int[] != int

您可以在整数数组一个整数的数据进行比较单一整数

定义的比较:int[x] != int

这会工作:a[x] != tervalx是你想检查的数组索引

考虑一下这个版本:

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); 

} 

从控制台获取用户输入:当用户进入

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" 
    } 
} 
+0

谢谢!但我仍然在我的IO代码中出现错误。 a = IO.readInt [];似乎没有工作。我猜测IO模块不能与数组一起使用?有没有其他解决方案? – javaisjusttoohard

+0

我仍然对'IO.readInt []'感到困惑......这不是有效的Java语法,据我所知。不是'System.in.read()'正确的语法吗? –

+0

我想要求用户输入数字在IO是我从班级学到的.. – javaisjusttoohard