我之前问过类似的问题,但我无法弄清楚问题是什么。我是编程新手,对如何通过将数组的初始长度设置为变量来更改数组的长度感到困惑,但它没有更新。
我的代码:
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();
}
}
}