1

那么你将如何将它与完全不同的java文件一起使用但在同一个包中

public static void main (int[] args)
{
int [] HotDog = {18,8,10,0};
int [] ToastedChicken = {25,8,17,0};
int [] ToastedSteak = {30,8,22,0};
int [] ToastedEggT= {20,8,6,6};
int [] ToastedSteakE={36,8,22,6};
int [] ChickenRoll = {25,8,17,0};
int [] SteakRoll = {30,8,22,0};
int [] EggTomato = {20,8,6,6};
int [] CheeseTomato = {20,8,6,6};
int [] steakEgg = {36,8,22,6};`

IE在这里

if (contents ==  "Hot Dog")

{jLabel2.setText(HotDog[2]); }  
4

3 回答 3

5

您需要将它们设为静态。例如:

final class MyConstants {
    static final int[] HotDog = {18, 8, 10, 0};
    static final int[] ToastedChicken = {25, 8, 17, 0};
    static final int[] ToastedSteak = {30, 8, 22, 0};
    static final int[] ToastedEggT = {20, 8, 6, 6};
    static final int[] ToastedSteakE ={36, 8, 22, 6};
    static final int[] ChickenRoll = {25, 8, 17, 0};
    static final int[] SteakRoll = {30, 8, 22, 0};
    static final int[] EggTomato = {20, 8, 6, 6};
    static final int[] CheeseTomato = {20, 8, 6, 6};
    static final int[] SteakEgg = {36, 8, 22, 6};

    private MyConstants() {
        // Prevents users of this class from instantiating a useless instance of
        // this class, since all members are static.
    }
}

然后您可以在同一个包中的任何类中使用它们,例如:

if (contents.equals("Hot Dog")) {
    jLabel2.setText(MyConstants.HotDog[2]);
}  
于 2012-09-05T18:39:29.797 回答
1

我将尝试将它们设置Arraystatic,因此所有尝试访问这些数组的类都会获得相同的数组...

我也可以Singleton Principle with Composition在这里使用......但这有点矫枉过正......

public class Test{
static int [] HotDog = {18,8,10,0};
static int [] ToastedChicken = {25,8,17,0};
static int [] ToastedSteak = {30,8,22,0};
static int [] ToastedEggT= {20,8,6,6};
static int [] ToastedSteakE={36,8,22,6};
static int [] ChickenRoll = {25,8,17,0};
static int [] SteakRoll = {30,8,22,0};
static int [] EggTomato = {20,8,6,6};
static int [] CheeseTomato = {20,8,6,6};
static int [] steakEgg = {36,8,22,6};

}

public class AccessIt{


Test.HotDog;


}
于 2012-09-05T18:42:00.103 回答
0

您的数组当前位于方法 main 的本地。如果将它们移到 main 方法之外(与它们完全一样),那么它们将对其他类可见,因为它们具有包访问权限。您将需要对该类的引用(除非您将它们设为静态)。在下面的示例中,我调用了 X 类

int [] HotDog = {18,8,10,0};
int [] ToastedChicken = {25,8,17,0};
int [] ToastedSteak = {30,8,22,0};
int [] ToastedEggT= {20,8,6,6};
int [] ToastedSteakE={36,8,22,6};
int [] ChickenRoll = {25,8,17,0};
int [] SteakRoll = {30,8,22,0};
int [] EggTomato = {20,8,6,6};
int [] CheeseTomato = {20,8,6,6};
int [] steakEgg = {36,8,22,6};`

public static void main (int[] args)
{
     jLabel2.setText(new X().HotDog[2]); //will return 10
}

此外,java 中的常见做法是在 camelCase 中命名变量。例如鸡卷

于 2012-09-05T18:39:36.193 回答