我想知道是否有可能更改下面的代码,第二个输出打印变更后的变量,我得到“2.2noo100onn”而不是“1.1foo200oof”?
是否可以从不同类型返回多个类型,或者我是否可以创建混合变量类型数组?
我正在处理的代码要大得多,但这个例子的工作原理相同。
public class test
{
static String s1 = "foo";
static String s2 = "oof";
static double d1 = 1.1;
static int i1 = 200;
public static void main (String[] args)
{
// Ausgabe Hello World!
System.out.println(d1+s1+i1+s2);
bla();
System.out.println(d1+s1+i1+s2);
}
public static void bla() {
String s1 = "noo";
String s2 = "onn";
double d1 = 2.2;
int i1 = 100;
}
}
答案 0 :(得分:5)
是的,你可以。
在方法bla()中,您重新声明变量,以便新变量具有局部范围。它们实际上是与您在课程开始时声明和初始化的变量不同的变量。相反,以这种方式操作类范围变量:
public static void bla() {
s1 = "noo";
s2 = "onn";
d1 = 2.2;
i1 = 100;
}
答案 1 :(得分:4)
如果您希望bla
方法更改静态变量,请不要隐藏它们。当您在该方法中重新声明这些变量时,您将创建新的局部变量,这些变量仅存在于方法的范围内。
将您的代码更改为:
public static void bla()
{
s1 = "noo";
s2 = "onn";
d1 = 2.2;
i1 = 100;
}
答案 2 :(得分:1)
public static void bla() {
String s1 = "noo"; //s1 is a local variable that's never used
String s2 = "onn";
double d1 = 2.2;
int i1 = 100;
//s1, s2, d1 and i1 will be destroyed and garbage collected here
}
您声明一个新的String对象并隐藏类成员。 s1
这里的字符串不是同一个字符串。
答案 3 :(得分:1)
试试这个......
public class test
{
static String s1 = "foo";
static String s2 = "oof";
static double d1 = 1.1;
static int i1 = 200;
public static void main (String[] args)
{
// Ausgabe Hello World!
System.out.println(d1+s1+i1+s2);
bla();
System.out.println(d1+s1+i1+s2);
}
public static void bla()
{
s1 = "noo";
s2 = "onn";
d1 = 2.2;
i1 = 100;
}
}