1

大家好,我是 Java 的初学者,我遇到了一些关于数组和数组列表的问题。我的主要问题是如何将计算、动态数据写入数组以及以后如何读取它?这是我奇怪的代码:

    public static void main(String[] args) {

    int yil, bolum = 0, kalan;
    Scanner klavye = new Scanner(System.in);
    ArrayList liste = new ArrayList();

    //or shall i use this? >> int[] liste = new int[10];

    System.out.println("Yıl Girin: "); // enter the 1453
    yil = klavye.nextInt();

    do{ // process makes 1453 separate then write in the array or arraylist. [1, 4, 5, 3]

    kalan = yil % 10;
    liste.add(kalan); //my problem starts in here. How can i add "kalan" into the "liste".
    bolum = yil / 10;
    yil = bolum;

    }while( bolum == 0 );

    System.out.println("Sayının Basamak Sayısı: " + liste.size()); //in here read the number of elements of the "liste" 
    klavye.close();
}

编辑:

    //needs to be like that
    while( bolum != 0 ); 
    System.out.println("Sayının Basamak Sayısı: " + liste);
4

4 回答 4

4

我认为您很可能希望您的循环停止条件为:

while( bolum != 0)

因为bolum只有0当您的号码中没有更多数字需要处理时才会出现。此外,正如上面提到的那样,可能是用户0在提示输入数字时输入的情况,因此您应该考虑到这一点。

于 2012-10-21T21:29:32.307 回答
1

要获得您的字符串表示形式ArrayList(通过字符串表示形式显示它包含的元素),您可以使用

System.out.println("Sayının Basamak Sayısı: " + liste);

无需转换为数组。这是有效的,因为它会导致liste'toString方法被调用(这就是我们不需要显式调用它的原因)。

于 2012-10-21T21:28:25.327 回答
0

You must change this line:

}while( bolum == 0 );

To this:

}while( bolum > 0 );
于 2012-10-21T21:31:45.890 回答
-1

如果要在 ArrayList 中打印元素,请将最后一条语句更新为打印如下:

  System.out.println("Sayının Basamak Sayısı: " + liste);

或者您可以迭代您的列表并打印为:

 for(Object i: liste){
    System.out.println(i);
 }

这将在单独的行中打印您的各个列表项。

另外请修复您的 while 条件,while(bolum != 0);因为它可能在第一次迭代后终止,bolum即非零 1, 2...(!= 0)

于 2012-10-21T21:25:38.453 回答