当前页面: 开发资料首页 → J2SE 专题 → 一道简单的java程序出错, 为什么?
一道简单的java程序出错, 为什么?
摘要: 一道简单的java程序出错, 为什么?
Mytest.java的代码如下:
class WaterSource {
private String s;
WaterSource() {
System.out.println(-#34;WaterSource()-#34;);
s = new String(-#34;Constructed-#34;);
}
public String toString() { return s; }
}
public class Mytest{
WaterSource source ;
source = new WaterSource();
void print() {
System.out.println(-#34;source = -#34; + source.toString());
}
public static void main(String args[]){
Mytest x = new Mytest();
x.print();
}
}
先声明一个对象, 再实例化出错, 错误提示:
Mytest.java:12: -#60;identifier-#62; expected
source = new WaterSource();
^
1 error。
如果把
WaterSource source ;
source = new WaterSource();
改成: WaterSource = new WaterSource();
后, 程序就能正常编译通过! 这是为什么呢?
...
source = new WaterSource();需要在方法中完成
class WaterSource {
private String s;
WaterSource() {
System.out.println(-#34;WaterSource()-#34;);
s = new String(-#34;Constructed-#34;);
}
public String toString() { return s; }
}
public class Mytest{
//WaterSource source ;
WaterSource source = new WaterSource();
void print() {
System.out.println(-#34;source = -#34; + source.toString());
}
public static void main(String args[]){
Mytest x = new Mytest();
x.print();
}
}
这样改一下就可以了
-----------------
WaterSource source ;//定义
source = new WaterSource();//这句被认为为赋值语句
赋值语句应该放在方法里
-----------------------
WaterSource = new WaterSource(); //定义
这么写 string 变量不好哦~~
s = new String(-#34;Constructed-#34;);
谢谢
public class Mytest中public 去掉也可以的