ArrayList.add方法不起作用

时间:2013-03-26 13:37:05

标签: java methods arraylist add

我是java的初学者,我不明白为什么这不起作用。我正在尝试编写一个程序,将基数为10的数字转换为二进制数,但我遇到了一个ArrayList的问题。我不能使用ArrayList的add方法:

import java.util.ArrayList;
import java.util.Scanner;

public class DecimalToBinary {
public static void main (String[] args){
    Scanner reader = new Scanner (System.in);

    System.out.println("This program converts a decimal number to binary.");

    int decimal;
    ArrayList<int[]> binary = new ArrayList<int[]>();

    //Gets decimal number
    System.out.print("Enter base 10 number: ");
    decimal = reader.nextInt();

    //Adds 1 to binary and then adds the remainders of decimal/2 after that until decimal is 1 
    binary.add(1, null);
    while (decimal != 1){
        binary.add(1, decimal%2);//This is where I get the error
        decimal = decimal/2;
    }//Ends While loop
}//Ends main

} //结束DecimalToBinary类

2 个答案:

答案 0 :(得分:1)

在这一行:

ArrayList<int[]> binary = new ArrayList<int[]>();

您声明ArrayList将只包含int类型的数组。换句话说,存储在'binary'中的每个对象都是int的数组。

所以,当你写:

binary.add(1, decimal % 2);

您正在尝试将'decimal%2'添加到二进制的位置1。因为十进制%2是一个int,而不是一个int数组,所以会出现编译器错误。

将二进制声明更改为:

ArrayList<Integer> binary = new ArrayList<Integer>();

答案 1 :(得分:0)

ArrayList <Integer> binary = new ArrayList <Integer>();

binary.add(3);
相关问题