我怎样才能声明一个空的int

How can I declare an empty int

我想声明一个空的 int,就像您对字符串所做的那样:String userName =""; 我需要一个空整数,因为我想 select 来自数组的(随机)图片:

public int[] mBackground = {
       R.drawable.heart,
       R.drawable.cane,
       R.drawable.watch
};

这是我用来从数组中获取随机图片的代码:

public int getBackground(){
int background = "";
    Random generate = new Random();
    int randomNumber = generate.nextInt(mBackground.length);

    background = mBackground[randomNumber];

    return background;
}

我不明白你的问题。为什么需要初始化呢?你甚至不需要变量。

此代码如您所愿

public int getBackground(){
    Random generate = new Random();
    int randomNumber = generate.nextInt(mBackground.length);
    return mBackground[randomNumber];
}

但是,如果你想要一个变量,你可以这样做

public int getBackground(){
    Random generate = new Random();
    int randomNumber = generate.nextInt(mBackground.length);
    int background = mBackground[randomNumber];
    return background;
}

如果出于某种原因必须为 int background 变量分配一个默认值,-1 通常是可行的。您不能将 int 变量分配给整数值以外的任何值(""String,因此不起作用)。

    int background = -1;
    // ...
    if (background < 0) {
        // handle invalid value, perhaps assign a default
    }

如果您需要变量指向 "nothing",请考虑使用盒装类型 Integer,您可以将其初始化为 null.

    Integer background = null; // will throw NullPointerException if unboxed to int

否则,在准备好赋值之前不要声明变量。这样你就不必给它一个毫无意义的初始值。

    int background = mBackground[randomNumber];

或者您可以 return 直接从您的方法中获取值,而不是将其分配给中间变量。

    return mBackground[randomNumber];

实际上,您根本不必在声明局部变量时对其进行初始化。这是完全可以接受的。

    int background;

但是,您必须先赋值才能使用它。

这是您的方法意图的最短陈述。

public int getBackground(){
    return mBackground[new Random().nextInt(mBackground.length)];
}

在您给出的上下文中没有空整数这样的东西,空字符串是包含长度为 0 的序列的字符串。 int 是一种原始数据类型,不能在有符号或无符号 32 位整数的参数之外取任何值,除非您想声明为 Integer boxed Object,在这种情况下您可以将其声明为 null。

对于从数组中选择随机值这样简单的方法,您也可以只使用一行代码。

public int getBackground(){
    return mBackground[new Random().nextInt(mBackground.length)];
}