[英]java, printing out mode
i am trying to get counts of modes, and modes as outputs but i am having some difficulties.我正在尝试获取模式计数,并将模式作为输出,但我遇到了一些困难。 Could you help me out?你能帮我吗?
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);
}
}
This line: while(a != terval)
contains a compilation error.这一行: while(a != terval)
包含一个编译错误。
int[] a
was never initialized so it has a null
a value when the loop begins. int[] a
从未被初始化,所以当循环开始时它有一个null
a 值。
int[] a
is an integer array and int terval
is an integer. int[] a
是一个整数数组, int terval
是一个整数。 The conditional a != terval
is undefined because you cannot compare an int array to an int.条件a != terval
未定义,因为您无法将 int 数组与 int 进行比较。
Undefined Comparison: int[] != int
未定义的比较: int[] != int
You can compare a single integer in the integer array to another single integer您可以将整数数组中的单个整数与另一个整数进行比较
Defined Comparison: int[x] != int
定义的比较: int[x] != int
This would work: a[x] != terval
where x
is an array index you want to check这会起作用: a[x] != terval
其中x
是您要检查的数组索引
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"
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.