如果把public E14_DefaultInitialization() {
System.out.println("i = " + i);
System.out.println("c = " + c);
System.out.println("s= "+s);
}
这一段去掉,System.out.println("s="+tt.s);
就会起作用,为何?
System.out.println("i = " + i);
System.out.println("c = " + c);
System.out.println("s= "+s);
}
这一段去掉,System.out.println("s="+tt.s);
就会起作用,为何?
public E14_DefaultInitialization() {
System.out.println("i = " + i);
System.out.println("c = " + c);
System.out.println("s= "+s);
}
不是构造函数:
注意它前面有public,如果去掉它就是构造函数,并能得到你预期的结果。
另:构造函数前面有public完全没有问题。
无限强,撅到运行结果
i = 0
c =
s= null
s=null有问题么楼主?
/--------------------------------------------------------------------吓我一跳
只要方法名和类名相同,没有返回类型的都是构造方法
我是希望得到这样的结果
i = 0
c =
s= null
s=null
但我得到缺是
i = 0
c =
后面两行却没有,但当我把构造函数去掉后,s=null就有了,所以我百思不得其解
i = 0
c =
s= null
s=null
不过c =后面是一个乱码的符号,当我copy all,并且pase到其他地方,记事本,或者这里的时候,只剩下
i = 0
c =
所以我改了你的程序
public class E14_DefaultInitialization {
int i;
char c;
String s;
public E14_DefaultInitialization() {
System.out.println("i = " + i);
String asd = new String("c = " + c);
System.out.println(asd);
byte bbb[] = asd.getBytes();
for(int j=0;j<bbb.length;j++) {
System.out.println(bbb[j]);
}
System.out.println("s= " + s);
}
public static void main(String args[]) {
E14_DefaultInitialization tt = new E14_DefaultInitialization();
System.out.println("s=" + tt.s);
}
}
运行结果如下
i = 0
c =
99
32
61
32
0
s= null
s=null
原来你的c = char(0),我想你的输出是因为遇到了char(0)而终止了后面的输出。
所以结论就是:养成初始化所有变量的好习惯
和初始化变量没关系,程序没问题,运行结果也没问题
i = 0
c =
s=null
s=null不知道楼主为什么会得到那样的结果
就算是为空值也应该String s="";
只要这样你就可以得到你结果的 !
无论在上面初始化还是在构造函数里面!有我这句话你就能得到你要得结果了
public class a
{
int i;
char c;
String s; public a()
{
System.out.println("i = " + i);
System.out.println("c = " + c);
System.out.println("s = "+s);
} public static void main(String[] a)
{
a tt = new a();
System.out.println("s = " + tt.s);
}
}输出结果:
i = 0
c =
s = null
s = null没问题呀!
楼主机器坏了吧! ~_~
而且我发现是因为机器在遇到System.out.println("c = " + c)这一句时就终止了。我又把程序改了一下,变成
System.out.println("i = " + i);
System.out.println("s= "+s);//把这一句移到上面
System.out.println("c = " + c);
结果输出是
i = 0
s = null
c =
但照理应该是
i = 0
s = null
c =
s = null//这一句没有被打印出来
这充分说明了程序在遇到System.out.println("c = " + c)这一句时就终止了。(至少在我的机器上就是这样的)我不明白!
如果你是用JCreator Pro 这工具的应该行!