我是Java的新手,正在开发一个基本程序,它可以查看数组并给出打印数组中可被3整除的数字。我在使其正常工作时遇到了一些麻烦。这是我到目前为止的代码。
package arraysearch;
public class Intsearch {
public static void main(String[] args) {
}
public static void multiple_3 (int[] a, int b) {
b=0;
}
{
int[] numarray ={3, 9, 45, 88, 23, 27, 68};
{
if (numarray % 3)==0;
b = b+1;
}
System.out.println("This is the amount of numbers divisible by 3:" +b)
}
}
答案 0 :(得分:5)
试试这个(Java 7):
public static void main(String[] args) {
multiple_3(new int[] { 3, 9, 45, 88, 23, 27, 68 });
}
public static void multiple_3(int[] ints) {
int count = 0;
for (int n : ints) {
if (n % 3 == 0) {
count++;
}
}
System.out.println("This is the amount of numbers divisible by 3: " + count);
}
public static void multiple_3(int[] ints) {
long count = IntStream.of(ints).filter(n -> n % 3 == 0).count();
System.out.println("This is the amount of numbers divisible by 3: " + count);
}
答案 1 :(得分:0)
您需要一个for循环来按顺序评估数组中的每个项目:
int[] numarray = { 1, 2, 3 };
for (int i = 0; i < numarray.Length; i++)
{
if (numarray[i] % 3 == 0)
{
b++;
}
}
答案 2 :(得分:0)
请尝试:
int b=0;
int[] numarray ={3, 9, 45, 88, 23, 27, 68};
for ( int i=0; i<numarray.length; i++)
{
if (numarray[i]%3==0)
b++;
}
System.out.println("This is the amount of numbers divisible by 3:" +b)