2012-11-18 198 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