请大家帮我补充一下程序代码

buchjava 2007-12-26 12:10:05

下面的程序代码可以运行,结果是:

第1次循环:
Hello world!
第2次循环:
您好,世界!
第3次循环:
HELLO WORLD!!
第4次循环:
数组越界
请按任意键继续. . .

但是我想把结果改变成像下面这样的结果,不知道这么改,请大家帮忙改一下。谢谢!
第一次循环:
Hello world!
第二次循环:
Hello world!
您好!世界!
第三次循环:
Hello world!
您好!世界!
HELLO WORLD!!
第四次循环:
数组越界...

public class TestException
{
public static void main(String[] args)
{
int i=0;
String ss[] = {"Hello world!","您好,世界!","HELLO WORLD!!"};
for (; i<4; i++ )
{
try
{
System.out.println("第" + (i+1) + "次循环:");
System.out.println(ss[i]);
}
catch (Exception e)
{
System.out.println("数组越界");
}

}
}
}
...全文
68 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
wxinb 2007-12-26
  • 打赏
  • 举报
回复
2楼,不知你用catch块输出“数组越界”是否欠佳呢?既然已经知道在何处有异常产生了,就没有必要让catch块捕捉程序中的异常的。

个人意见。
wxinb 2007-12-26
  • 打赏
  • 举报
回复
1楼!你给的程序(if(i>=ss.length-1))有问题。if(i>=ss.length-1) => if(i>=ss.length)修正后:
int i = 0;
String ss[] = {"Hello world!","您好,世界!","HELLO WORLD!!"};
for (; i < 4; i++) {
System.out.println("第" + (i+1) + "次循环:");
if (i >= ss.length) {
System.out.println("数组越界");
} else {
for (int j = 0; j <= i; j++) {
System.out.println(ss[j]);
}
}
}
楼主,试试我的程序吧,我运行过,没有问题的,与你想要的结果是一样的!
ooo19841080xinxin 2007-12-26
  • 打赏
  • 举报
回复
public class TestException
{
public static void main(String[] args)
{
int i=0;
String ss[] = {"Hello world!","您好,世界!","HELLO WORLD!!"};
for (; i <4; i++ )
{
int j=0;
System.out.println("第" + (i+1) + "次循环:");
if(i==ss.length)
j=3;
for(;j<i+1;j++)
{
try
{
System.out.println(ss[j]);
}
catch (Exception e)
{
System.out.println("数组越界");
}
}

}
}
}
huoyin 2007-12-26
  • 打赏
  • 举报
回复
public class TestException {
public static void main(String[] args) {
int i = 0;
String ss[] = { "Hello world!", "您好,世界!", "HELLO WORLD!!" };
for (; i < 4; i++) {
System.out.println("第" + (i + 1) + "次循环:");
if(i>=ss.length-1){
System.out.println("数组越界");
} else {
for (int j = 0; j <= i; j++) {
System.out.println(ss[j]);
}
}
}
}
}
phyeas 2007-12-26
  • 打赏
  • 举报
回复
我也来一段。呵呵。测试只需要将0传入方法即可

String[] ss={"Hello world!","您好,世界!","HELLO WORLD!!"};

public void testStringArray(int index){
if(index<ss.length){
for(int i=0;i<=index;i++){
System.out.println (ss[i]);
}
testStringArray(index+1);
}else{
System.out.println ("数组越界");
}
}

62,623

社区成员

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

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