この問題は私には:与えられた配列をテストし、そこに番号5があるかどうかを確認する必要があります。 5がある場合はFalseを返します。それ以外の場合はtrueを返します。私はそれを働かせました...まあ、私はそれが効率的な方法ではないことを知っています。唯一の問題は、ケース1とケース6の場合、私はError java.lang.ArrayIndexOutOfBoundsException
を得ています。なぜかわからないのです。残りはうまく動作します。配列に特定の値があるかどうかを調べるにはどうすればよいですか?
import java.util.*;
public class testCases
{
public static void main(String[] args)
{
Scanner kb = new Scanner(System.in);
System.out.print("Which case do you wish to test? ");
int testCase = kb.nextInt();
switch(testCase)
{
case 1:
System.out.println("noFives(1, 2, 3, 4) = " + noFives(1, 2, 3, 4, 6));
break;
case 2:
System.out.println("noFives(1, 2, 3, 4, 5) = " + noFives(1, 2, 3, 4, 5));
break;
case 3:
System.out.println("noFives(1, 2, 5, 3, 4) = " + noFives(1, 2, 5, 3, 4));
break;
case 4:
System.out.println("noFives(5, 1, 2, 3, 4) = " + noFives(5, 1, 2, 3, 4));
break;
case 5:
System.out.println("noFives(27, 82, 4, 71, 6, 23, 9, 18) = " + noFives(27, 82, 4, 71, 6, 23, 9, 18));
break;
case 6:
System.out.println("noFives(0) = " + noFives(0));
break;
case 7:
System.out.println("noFives(5) = " + noFives(5));
break;
default:
System.out.println("noFives() = " + noFives());
}
}
public static boolean noFives(int ... n)
{
if(n.length == 0)
return true;
else if(n[0] == 5 || n[1] == 5 || n[2] == 5 || n[3] == 5 || n[4] == 5 || n[5] == 5 || n[6] == 5 || n[7] == 5)
return false;
else
return true;
}
}
'Arrays.stream(アレイ).filter(X - > X == 5).collect(Collectors.toList).size()== 0 '? – alfasin
@apples forループを使用して配列を繰り返し処理するだけで簡単です –