异常抛出

bob21 2005-03-29 01:16:46
有个关于异常的练习题,如下:

输入一个密码,必须由7个字符组成,其中最少有1个数字。写出一个程序,读取该的密码,并且验证该密码是否符合要求。如不符合要求,抛出一个异常,告知输入错误,并重新输入。

各位大虾帮忙,小弟在此请教了。
...全文
134 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
Hodex 2005-03-30
  • 打赏
  • 举报
回复
字符截取:char chatAt(int where)
void getChars(int sourceStart,int sourceEnd,char target[],int targetStart)
Hodex 2005-03-30
  • 打赏
  • 举报
回复
呵呵,祝贺了
bob21 2005-03-30
  • 打赏
  • 举报
回复
感谢大家,我昨晚已经把问题解决了。有2个方法:
1:

…………
for(int i=0;i<s.length();i++)
{
ch=s.charAt(i);
if(((int)ch>47)&&((int)ch<58 ))
…………
}
…………

——————————————————————————————————————
2:

String input;
input = "fdsf2";
int n = 0;

for(int i = 0; i < input.length(); i++)
{
if(Character.isDigit(input.charAt(i)))
n++;
}

if(n == 0)
System.out.println("There is no number in this string.");
else
System.out.println("There is number(s) in this string.");
sakura8sakura 2005-03-29
  • 打赏
  • 举报
回复
参考下面代码

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Test {

public static void chkPwd(String strPwd) throws Exception{
System.out.println("the password is : " + strPwd);
Pattern p = Pattern.compile("[0-9a-zA-Z]*[0-9][0-9a-zA-Z]*");
Matcher m = p.matcher(strPwd);
boolean b = m.matches();
if(b==false || strPwd.length()!=7)
throw new Exception("Password is error!");
}
public static void main(String[] args) {
boolean bln=false;
while(bln == false){
String strPwd = "";
byte[] bytPwd = new byte[1];
try{
int b;
while((b=System.in.read(bytPwd))>0){
if("\r".equals(new String(bytPwd))) continue;
if("\n".equals(new String(bytPwd))) break;
strPwd += new String(bytPwd);
}
chkPwd(strPwd);
bln = true;

}catch(Exception e){
System.out.println(e.toString());
}
}
System.out.println("Password is right!");
}
}
bob21 2005-03-29
  • 打赏
  • 举报
回复
谢谢各位解答,谢谢楼上的代码,不过楼上的代码有些复杂,看不太懂。

这道题的思路我是有,我知道用length计算长度,用for逐个检查7个字符中是否有最少一个数字。问题是在这里,我用String input = JOptionPane.showInputDialog("Enter 7 characters for password");来读取输入,我用for怎么来判断其中有无数字,把String变成7个char吗?就是这里我不知该怎么做。
topil 2005-03-29
  • 打赏
  • 举报
回复
你可以写个checkInput的方法来判断输入是否合法,至于exception是用于程序扑获的,最好不要通过抛出异常来控制程序的流程。
007remember 2005-03-29
  • 打赏
  • 举报
回复
路过
学习ing
顶下帮
Hodex 2005-03-29
  • 打赏
  • 举报
回复
不用try,只要不符合要求就直接throw new Exception("密码不符合");
OnlyFor_love 2005-03-29
  • 打赏
  • 举报
回复
楼上说的对啊!自己写,多简单啊,思路在你的练习题要求中已经很明显了!
比如“必须由7个字符组成”,这句你就可以通过length来计算长度是否满足!
“其中最少有1个数字”,这句就说明你可以通过循环语句来判断!
“如不符合要求,抛出一个异常”,这句你就用捕捉异常来实现,要是不满足要求,你就抛出异常就行了!
fdabobi 2005-03-29
  • 打赏
  • 举报
回复
很简单的一个小程序啊,难道要全部代码??
最简单的实现思路就
1.用pass.length计算长度是否符合
2.用for语句逐个检查
3.给所有语句套上try块,遇到以上两项检查碰到不符合的地方throw一个自己定义的exception类
这是最基本的代码,建议你还是自己手写,如果这也要别人给你代码的话
你是学不下去的

62,614

社区成员

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

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