如何编写没有长度的数组

时间:2015-11-13 16:44:09

标签: java

我正在尝试编写一个程序,在数组中查找三个数字,给出一个长度为3的算术序列 - 三个数字a,b和c形成一个长度为3的算术序列,如果:ba = cb。

我有两个问题:

  1. 我需要读取一个任意数字类型的int,并将它们放在一个数组中。例如:java string 3 4 5 6,给出数组:[3],[4],[5],[6]。 我无法做到这一点,因为在创建一个数组时,它要求数组长度。

  2. 我在为b-a = c-b编写数学命令时遇到问题。

  3. public static void main (String[] args) {
    
        int [] a = new int [10];
        for (int i = 0; true; i++) {
          a[i] = Integer.parseInt(args[i]);
        }
    
        System.out.println(a.length);
        for (int i = 0; i < a.length; i++) {
    
          for (int j=i+1; j<a.length; ++j) {
            int sum = a[i]-a[j];
            int tempa = a[i];
            int d = a[i+1];
            int c = a[i+2];
            if (d == tempa+d && c == tempa +  2*d)
                System.out.println("yes");
    
            }
         }
    }
    

3 个答案:

答案 0 :(得分:0)

您有两个选择

选项1 - 提前询问长度

我认为这个选项不需要太多解释。它看起来像这样

Scanner in = new Scanner(System.in);
int length = in.nextInt();
//... use "length" as you wish

选项2 - 使用ArrayList

您的代码看起来会像这样:

int inputNum = in.nextInt();
ArrayList<Integer> a = new ArrayList<Integer>();
while (inputNum != 1){
    a.add(inputNum);
}
//you can use "a" as you wish now

答案 1 :(得分:0)

正如评论中已提到的,使用ArrayList动态更改列表的大小。然后,您可以在需要时使用for f in `find ./ -name '*.py'`; do echo $f; if [ -x $f ]; then echo $f 'is executable setting svn:executable'; svn propset svn:executable on $f; else echo $f 'is not executable'; fi; done; 分配值。查看官方documentation了解更多详情。

答案 2 :(得分:0)

对于您的第一个问题,从String创建一个整数数组已经拥有了大部分内容。您还没想到args数组的大小是要解析的String值的数量。您已经知道如何使用length的{​​{1}}属性。

这是我的解决方案:

array
相关问题