初学Java循环输入错误,帮忙看下,谢谢!

z275599707 2009-03-30 06:32:56
import java.io.*;
public class ExpermentFour_two
{
/**
* @param args
* Experment_Four_two
*/
public static void main(String[] args)
{
// TODO Auto-generated method stub
String str=new String("");
int i=0;
int len=0;
int flag=0;
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter a number:");
do
{
try
{
str=in.readLine();
}
catch(IOException e)
{
System.out.print("ERROR!");
System.exit(0);
}
len=str.length();
for(i=0;i<len;i++)
{
if(str.charAt(i)<'0'||str.charAt(i)>'9'||str.charAt(0)=='0')
{
System.out.println("输入错误,重新输入!");
str=null;
flag=1;
break;
}
}
}while(flag==1);
for(i=0;i<len/2;i++)
{
if(str.charAt(i)!=str.charAt(len-i-1))
{
System.out.println("输入的数字是"+len+"位数 ,不是回文数! ");
return ;
}
}
System.out.println("输入的数字是"+len+"位数 ,是回文数! ");

}

}
...全文
82 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
xjun15 2009-03-30
  • 打赏
  • 举报
回复
if(str.charAt(i) <'0'||str.charAt(i)>'9'||str.charAt(0)=='0')
当这个判断为真时,flag将被值1,程序一直做do while循环,退不出来,楼上正解!
z275599707 2009-03-30
  • 打赏
  • 举报
回复
谢谢楼上哈,呵呵,这个竟然忘了!
台城柳月 2009-03-30
  • 打赏
  • 举报
回复
public static void main(String[] args) throws Exception {
String str=new String("");
int i=0;
int len=0;
int flag=0;
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter a number:");
do
{
try
{
str=in.readLine();
}
catch(IOException e)
{
System.out.print("ERROR!");
System.exit(0);
}
len=str.length();
for(i=0;i<len;i++)
{
if(str.charAt(i)<'0'||str.charAt(i)>'9'||str.charAt(0)=='0')
{
System.out.println("输入错误,重新输入!");
str=null;
flag=1;
break;
}
}
if (str != null) flag = 0; // 这里加上这句就可以了
}while(flag==1);
for(i=0;i<len/2;i++)
{
if(str.charAt(i)!=str.charAt(len-i-1))
{
System.out.println("输入的数字是"+len+"位数 ,不是回文数! ");
return ;
}
}
System.out.println("输入的数字是"+len+"位数 ,是回文数! ");


}
z275599707 2009-03-30
  • 打赏
  • 举报
回复
但是输入错误的后比如:
Enter a number:
03
输入错误,重新输入!
30
这是光标就在这里闪
.....
台城柳月 2009-03-30
  • 打赏
  • 举报
回复
好像没有错

62,614

社区成员

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

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