2013-10-17 50 views
0

我之前问过类似的问题,但我无法弄清楚问题所在。我是编程新手,对如何通过将其初始长度设置为变量来更改数组的长度感到困惑,但它并未更新。如何更改数组的长度

我的代码:

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

回到上一个问题,您根本不需要更改数组的长度。既然你只想知道1和10之间的数字是否已经被猜测过,就有一个长度为10的**布尔型**数组。如果数字“n”被猜测出来,则将数组的值设置在索引'n - 1'为真。如果数组中的值已经为true,则不要再猜测它。 –

+1

当您的数组长度未知时,使用ArrayList –

回答

0

你不能改变Java中的数组的长度。您需要创建一个新的并复制这些值,或使用ArrayList

2

在Java中创建数组后,无法更改数组的长度。相反,必须分配一个新的更大的数组,并且必须复制这些元素。幸运的是,List接口的实现已经为您做了幕后工作,其中最常见的是ArrayList

顾名思义,ArrayList包装了一个数组,提供了通过如add()remove()(请参阅前面链接的文档)的方法添加/删除元素的方法。如果内部数组填满,则会创建一个大1.5倍的新数组,旧元素将被复制到它,但这些对您来说都是隐藏的,这非常方便。

1

我建议使用arrayList来代替。它会根据需要调整大小。在导入java.util.ArrayList后使用ArrayList<Integer> list=new ArrayList<>();创建它。

您可以按如下方式设置值。要在位置i设定值的值VAL,使用方法:

list.set(i, val); 

您可以添加到年底与list.add(someInt);int foo=list.get(position)检索。

仅通过将数组复制到较大数组的方式来“调整数组大小”是可能的。 仍然生成一个新的数组,而不是在适当的地方操作。 intInteger转换在这里通过自动装箱处理。

+2

调整数组大小是不可能的。您的脚注不涉及调整预分配数组的大小,而是创建一个* new *更大的数组。 – arshajii

+0

@arshajii对不起。修正在编辑中添加。 – hexafraction

0

正如其他人指出的,不要使用数组,请使用ArrayList。