나는 전에 비슷한 질문을했지만 문제가 무엇인지 알 수 없었다. 나는 프로그래밍에 익숙하지 않고 초기 길이를 변수로 설정하여 배열의 길이를 변경하는 방법에 대해 혼란 스럽지만 업데이트하지는 않습니다.배열의 길이를 변경하는 방법
내 코드 :
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 '사실. 배열의 값이 이미 참이면 다시 추측하지 마십시오. –
배열의 길이를 알 수없는 경우 ArrayList를 사용하십시오. –