我之前問過類似的問題,但我無法弄清楚問題所在。我是編程新手,對如何通過將其初始長度設置爲變量來更改數組的長度感到困惑,但它並未更新。如何更改數組的長度
我的代碼:
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 –