Java 什么';在一个数组中加三个数字得到30是错误的
我想把三个小于15的奇数相加得到30 这是我的密码:Java 什么';在一个数组中加三个数字得到30是错误的,java,indexoutofboundsexception,Java,Indexoutofboundsexception,我想把三个小于15的奇数相加得到30 这是我的密码: import java.util.*; public class odd { public static void main(String args[]) { int n[]={1,3,5,7,9,11,13,15}; int a,n1,n2,n3; Random rand=new Random(); do { n1=n[(rand.nextInt(8)+1)
import java.util.*;
public class odd {
public static void main(String args[]) {
int n[]={1,3,5,7,9,11,13,15};
int a,n1,n2,n3;
Random rand=new Random();
do {
n1=n[(rand.nextInt(8)+1)];
n2=n[(rand.nextInt(8)+1)];
n3=n[(rand.nextInt(8)+1)];
a=n1+n2+n3;}while(a!=30);
System.out.println(n1);
System.out.println(n2);
System.out.println(n3);
}
}
我得到以下异常:
线程“main”java.lang.ArrayIndexOutOfBoundsException中的异常:8
位于oddno.odd.main(odd.java:12)
数组有8个元素,索引范围为0到7 因此改变
n1=n[(rand.nextInt(8)+1)];
n2=n[(rand.nextInt(8)+1)];
n3=n[(rand.nextInt(8)+1)];
到
或者正如阿克塞尔所建议的:
n1=n[rand.nextInt(n.length)];
n2=n[rand.nextInt(n.length)];
n3=n[rand.nextInt(n.length)];
这里
当您从
0
到7
获取索引时。没有索引为8
的元素。这种方法很可怕。首先,如果总和无法达到,它将无限循环。设计算法至少和实现一样重要。考虑一些更聪明的方法:
至于您的实际错误,这取决于Java中的数组是基于零的:
n
范围从n[0]
到n[7]
。如果必须随机选取,则使用rand.nextInt(n.length)
该数组中的三个数字总和不能为30。请阅读有关的基本知识。使用n.length可以更改表的de-length,而无需输入代码。
n1=n[rand.nextInt(n.length)];
n2=n[rand.nextInt(n.length)];
n3=n[rand.nextInt(n.length)];
int n[]={1,3,5,7,9,11,13,15}; // size of array is 8