那么你如何使用完全不同的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]); }
答案 0 :(得分: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]);
}
答案 1 :(得分:1)
我会尝试将那些Array
设为static
,因此尝试访问这些数组的所有类都会获得相同的数组...
我本可以在这里使用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;
}
答案 2 :(得分: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中的comon实践也是在camelCase中命名变量。例如chickenRoll