当前位置: 代码迷 >> Java相关 >> [求助],帮我看一下呀
  详细解决方案

[求助],帮我看一下呀

热度:367   发布时间:2004-08-05 15:23:00.0
[求助],帮我看一下呀

public class test13{ public int i; public String s=""; public test13(){ i=5; s="liyang"; } public static void main(String[] args){ new test13(); System.out.println("i="+i); System.out.println("s="+s); } }

运行时总有错误:

[此贴子已经被作者于2004-08-05 15:43:55编辑过]


----------------解决方案--------------------------------------------------------

你的这个是一个很奇怪的程序

1,Test13 is a class, 我建议你用大写来命名

2. i 和 s 是Test13下的private variable(int)/object(String),所以,应该是private int i; private String s;

如果你一定要让它们成为public,那么就必须把它们定义为static: public static int i; public static String s; (although this is very very unusual!! I suggest avoid it)

3.new test13();<<这一行我想你是要建立一个instance of the Test13class, 要建立一个instance/obect, 格式是这样的:

ClassName instaceName = new ConstructorName(parameters);

in this case:

Test13 test = new Test13(); //where the name of test can be varied as u want

4.假设你的i 和s都是public,那么根本没有必要来建立一个新的instance test,要print只要System.out.println(i)就可以.可是我觉得你这里的意图是要用建立的Test13的object来call出i 和s,那么,应该是

System.out.println("i="+test.i);

System.out.println("s="+test.s);

summary as the following:

public class Test13{ private int i; private String s="";

public Test13(){ i=5; s="liyang"; } public static void main(String[] args){ Test13 test = new Test13(); System.out.println("i="+test.i); System.out.println("s="+test.s); } } //although this progarm works pretty well, but the more general way of doing such thing will be

public class Test13{ private int i; private String s="";

public Test13(){ i=5; s="liyang"; } public int getInt(){ // this is an accessor method which return the value of int i return i; } public String getString(){ // this is an accessor method which returns the String s return s; } public static void main(String[] args){ Test13 test = new Test13(); System.out.println("i="+test.getInt()); System.out.println("s="+test.getString()); } }


----------------解决方案--------------------------------------------------------
真的十分的感谢老大,
----------------解决方案--------------------------------------------------------
又有问题了???

我有两个java(1.java和2.java)文件,放在同一目录下,其中一个文件(2.java)要用另一个(1.java),当我用在2.java中有import 1;后,编译不了,提示:

E:\testofmy>javac 1.java

E:\testofmy>javac 2.java 2.java:2: '.' expected import 1; ^ 1 error

当我再把import 1;去掉后,又正常了,为什么

[此贴子已经被作者于2004-08-06 17:09:02编辑过]


----------------解决方案--------------------------------------------------------
最近老看不到版主大人啊?

类痴狂人大人最近老看不到耶

他最近还好么。呵呵。


----------------解决方案--------------------------------------------------------
老大~有没有用package语句啊?同一目录下是一个包,即默认包,所以不用import
----------------解决方案--------------------------------------------------------
  相关解决方案