请进

skyboy0720 2003-10-17 08:25:35
import java.io.*;
public class Teststr
{
public static void main ( String [ ] args ) throws IOException
{
String str1,str2;
char [ ] strArr = new char [ 10 ];
byte [ ] buff = new byte [ 10 ];
System.out.print ( "Input a string: " );
System.in.read ( buff, 0, 10 );
str1 = new String ( buff );
System.out.print ( "The string is : " + str1 );
// 反向输出字符串
for ( int i = str1.length ( ) - 1; i >= 0; i-- )
{
strArr [ str1.length ( ) - 1 - i ] = str1.charAt ( i ) ;
}
str2 = new String ( strArr );
System.out.println ( "The other string is : " + str2 );
//回文判断
if ( ( str2.compareTo ( str1 ) ) == 0 )
{
System.out.print ( "是回文" );
}
else
{
System.out.print ( "不是回文" );
}
}
}

例如我输入“12321”,反相也输出“12321”,但是在字符串比较上总是不相等,用equals或者
equalsIgnoreCase方法,总是得出不相等的结果,为什么呢,要怎样修改?
...全文
56 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
skyboy0720 2003-10-17
  • 打赏
  • 举报
回复
谢谢,我明白了!
LoveRose 2003-10-17
  • 打赏
  • 举报
回复
把System.out.print ( "The string is : " + str1 );
改成 System.out.println ( "The string is : ");
System.out.println (str1);

把System.out.println ( "The other string is : " + str2 );
改成 System.out.println ( "The other string is : ");
System.out.println(str2 );

就可以看到结果了:
你预想的结果应该是:
The string is :
12321
The other string is :
12321
是回文

而运行结果是
The string is :
12321

The other string is :

12321
不是回文
中间多处空行
LoveRose 2003-10-17
  • 打赏
  • 举报
回复
肯定不是相等的
虽然显示的结果是一样的其实并不一样
str1应该是“12321 ”
而str2应该是“ 12321”
结果当然不一样了

62,614

社区成员

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

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