[英]java, printing out mode
我正在嘗試獲取模式計數,並將模式作為輸出,但我遇到了一些困難。 你能幫我嗎?
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);
}
}
這一行: while(a != terval)
包含一個編譯錯誤。
int[] a
從未被初始化,所以當循環開始時它有一個null
a 值。
int[] a
是一個整數數組, int terval
是一個整數。 條件a != terval
未定義,因為您無法將 int 數組與 int 進行比較。
未定義的比較: int[] != int
您可以將整數數組中的單個整數與另一個整數進行比較
定義的比較: int[x] != int
這會起作用: a[x] != terval
其中x
是您要檢查的數組索引
考慮這個修訂:
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"
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.