双色球代码出现null值 求大神现身相助
运行几次有时候出现null 想不明白啊 求指点
package com.xxxx.d03;
import java.util.Arrays;
import java.util.Random;
public class TwoColorBalls02 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String[] thenumber=getTheNumber();
System.out.println(Arrays.toString(thenumber));
}
private static String[] getTheNumber() {
// TODO Auto-generated method stub
String[] poolStrings={
"01","02","03","04","05","06","07","08","09","10","11","12","13","14","15"
,"16","17","18","19","20","21","22","23","24","25","26","27","28","29","30",
"31","32","33"
};
Random random=new Random();
String[] redBalls=new String[6];//6个红球
// System.out.println(redBalls.length);
Lab:for (int i = 0; i < redBalls.length; i++) {
int index = random.nextInt(33);
String getBalls=poolStrings[index];
//保证不重复
for (int j = 0; j < redBalls.length; j++) {
if (getBalls.equals(redBalls[j])) {
continue Lab;
}
}
redBalls[i]=poolStrings[index];
}
String blueBalls=(1+random.nextInt(16))+"";//一个篮球
//copyOf应该是redBalls
String[] theBalls=Arrays.copyOf(redBalls, redBalls.length+1);
theBalls[theBalls.length-1]=blueBalls;
return theBalls;
}
}
random
continue
null
------解决方案--------------------continue LAB 的时候 i++也执行了啊 。 把他移下来就好了。
Lab: for (int i = 0; i < redBalls.length; ) {
int index = random.nextInt(33);
String getBalls = poolStrings[index];
// 保证不重复
for (int j = 0; j < redBalls.length; j++) {
if (getBalls.equals(redBalls[j])) {
continue Lab;
}
}
redBalls[i] = poolStrings[index];
i++;
}
------解决方案--------------------boolean flag = true;
int index = 0;
while(flag) {
int randomNumber = random.nextInt(33);
String getBalls=poolStrings[randomNumber];
//System.out.println("randomNumber值:" + randomNumber + "\t" + "getBalls:" + getBalls);
boolean isInsert = true;
for(int i = 0; i < redBalls.length; i++) {
if(getBalls.equals(redBalls[i])) {
isInsert = true;
break;
}
}
if(isInsert) {
redBalls[index] = getBalls;
index++;
if(index >= redBalls.length) {
flag = false;
}
}
}
不用for 你的那个循环 当是重复的时候,会index++ 那么当前的那个值并没有填充到 自然是null 然会直接跳到去填充下一个值了
------解决方案--------------------你用断点运行一下就知道哪里报的空了。