打印置换字符串的问题

lyjlee 2003-08-01 08:26:15
给出字符串(abc)希望实现:abc,acb,bac,bca,cab,cba的输出,程序如下:

import java.lang.*;

public class P412
{
public static void prt(int n,String str)
{
if (n<1)
{ return;
}
else if (n==1)
{
System.out.println(str);
}
else
{
for(int i=0;i<n;i++){
char tmpc=str.charAt(i);
String lft;
String rght;
if (i>0)
lft=str.substring(0,i-1);
else
lft="";
if(i<n)
rght=str.substring(i+1,n-1);
else
rght="";
String tmps=lft+rght;
System.out.print(tmpc);
prt(n-1,tmps);
}
}
}
public static void main(String[] args)
{
prt(3,"abc");
//System.out.println("Hello World!");
}
}


编译通过,运行出错,提示:

ab
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String ind
ex out of range: 1
at java.lang.String.charAt(String.java:455)
at P412.prt(P412.java:17)
at P412.prt(P412.java:30)
at P412.main(P412.java:36)

请高手指点,谢谢
...全文
31 1 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
xiaohuajx 2003-08-01
  • 打赏
  • 举报
回复
rght=str.substring(i+1,n-1);
有问题当i = n-1的时候出错;
下面是:substring方法的说明;
//
public String substring(int start,int end)
//
Returns a new String that contains a subsequence of characters currently contained in this StringBuffer. The substring begins at the specified start and extends to the character at index end - 1. An exception is thrown if
//Parameters:
start - The beginning index, inclusive.
end - The ending index, exclusive.
//Returns:
The new string.
//Throws:
StringIndexOutOfBoundsException - if start or end are negative or greater than length(), or start is greater than end.

62,630

社区成员

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

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