简单问题,为什么会出错?

JollySandy 2004-03-28 09:53:08
以下代码能通过编译,但运行出错,为什么?
import java.lang.*;
import java.io.*;

public class test
{
public void main (String args[])
{
temp t = new temp ();
t.temp = new String[] {"temp[0]", "temp[1]"};
t.tt = "tt string";
for (int i = 0; i < 3; i++) {
try {
System.out.print (t.temp1 (i));
System.out.println (t.tt ());
} catch (Exception e) {
e.toString ();
}
}
}

class temp
{
public String temp[];
public String tt;

public String temp1 (int i)
{
return temp[i];
}

public String tt ()
{
return tt;
}
}
}
...全文
64 13 打赏 收藏 转发到动态 举报
写回复
用AI写文章
13 条回复
切换为时间正序
请发表友善的回复…
发表回复
Ardor007 2004-03-29
  • 打赏
  • 举报
回复
public static void main (String args[])
wwj0213 2004-03-29
  • 打赏
  • 举报
回复
我的方法在我的机器上面运行是成功的,要不然你的环境配置就可能有问题。
kangfuguanxianjun 2004-03-29
  • 打赏
  • 举报
回复
public 为访问修饰符,可以控制那些部分可以访问本代码。
class 为关键字,表明java程序的任何部分都忖在于一个类中。
java的任何部分都存在类中。
static方法必须访问static成员
creaker 2004-03-29
  • 打赏
  • 举报
回复
补充:
1.public static void main(String[] args)必须如此, JVM的入口.
2.static方法必须访问static成员
creaker 2004-03-29
  • 打赏
  • 举报
回复
import java.lang.*;
import java.io.*;

public class test
{
public static void main (String args[])
{
temp t = new temp ();
t.temp = new String[] {"temp[0]", "temp[1]"};
t.tt = "tt string";
for (int i = 0; i < 3; i++) {
try {
System.out.print (t.temp1 (i));
System.out.println (t.tt ());
} catch (Exception e) {
e.toString ();
}
}
}

static class temp
{
public String temp[];
public String tt;

public String temp1 (int i)
{
return temp[i];
}

public String tt ()
{
return tt;
}
}
}
dengsf 2004-03-29
  • 打赏
  • 举报
回复
因为 main 方法必须是静态的,还要在前面加上 static 才行。
JollySandy 2004-03-28
  • 打赏
  • 举报
回复
to "wwj0213(郁闷天使)":
你的方法还是不行,仍然出现这个错误:
Exception in thread "main" java.lang.NoSuchMethodError:main
JollySandy 2004-03-28
  • 打赏
  • 举报
回复
Exception in thread "main" java.lang.NoSuchMethodError:main

另外,to“caiyanying732(学习)”:
如果加static的话就不能用动态分配new,应如何解决?
wwj0213 2004-03-28
  • 打赏
  • 举报
回复
把你的class temp{···}这一段提到class test{···}外面分别保存,先编译class temp,再编译class test;程序就可以执行成功!
caiyanying732 2004-03-28
  • 打赏
  • 举报
回复
public static void main(String args[]){
caiyanying732 2004-03-28
  • 打赏
  • 举报
回复
public void main (String args[])
函数加static成静态
sagittarius1979 2004-03-28
  • 打赏
  • 举报
回复
t.temp = new String[] {"temp[0]", "temp[1]"};
只是两维。。

for (int i = 0; i < 3; i++) {
try {
System.out.print (t.temp1 (i));
System.out.println (t.tt ());
} catch (Exception e) {
e.toString ();
}
}
但是输出
0,1,2三维,
所以报错
leeak 2004-03-28
  • 打赏
  • 举报
回复
出错在哪 贴出来最好

62,622

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧