我之前问过类似的问题,但我无法弄清楚问题所在。我是编程新手,对如何通过将其初始长度设置为变量来更改数组的长度感到困惑,但它并未更新。如何更改数组的长度
我的代码:
import java.util.Scanner;
class computer{
int g = 1; //create int g = 2
int[] compguess = new int[g]; //set array compguess = 2
void guess(){
int rand; //create int rand
int i; //create int i
rand = (int) Math.ceil(Math.random()*10); // set rand = # 1-10
for (i = 0; i < compguess.length; i++){ // start if i < the L of the []-1 (1)
if(rand == compguess[i]){ //if rand is equal to the Ith term, break the for loop
break;
}
} //end of for loop
if(i == compguess.length - 1){ //if i is = the length of the [] - 1:
compguess[g - 1] = rand; // set the new last term in the [] = rand
g++; // add 1 to the length of the [] to make room for another int
System.out.println(compguess[g - 1]); // print the last term
}
}
}
public class game1player2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
computer computer1 = new computer(); // create new computer object
for(int a = 0; a < 3; a++){ // start if a < 3
computer1.guess(); // start guess method
for(int n = 0; n < computer1.compguess.length; n++) //print the contents of []
System.out.println(computer1.compguess[n]); // print out entire array
}
{
input.close();
}
}
}
回到上一个问题,您根本不需要更改数组的长度。既然你只想知道1和10之间的数字是否已经被猜测过,就有一个长度为10的**布尔型**数组。如果数字“n”被猜测出来,则将数组的值设置在索引'n - 1'为真。如果数组中的值已经为true,则不要再猜测它。 –
当您的数组长度未知时,使用ArrayList –