首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > J2SE开发 >

看看哪位高手能有更简单的方法,大牛们出招吧!

2012-06-08 
看看谁能有更简单的方法,大牛们出招吧!!!!!!今天比较闲暇,写了一个小程序,就是一个登录相关的从键盘中输入

看看谁能有更简单的方法,大牛们出招吧!!!!!!

今天比较闲暇,写了一个小程序,就是一个登录相关的

从键盘中输入,用main方法接收,user:abc 和password:123

当输入错误时,应该再次输入用户名和密码,知道正确为止。

以下是我的实现方式,我想看看谁有更简单的没有,欢迎指点:

LoginEntity

Java code
public class LoginEntity {    private String name;    private String password;        public LoginEntity(String name,String password){        this.name = name;        this.password = password;    }        public boolean validate(){        if(name.equals("abc")&&password.equals("123")){            return true;        }else{            return false;        }                }}


Operate
Java code
import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;public class Operate {    private String str[];        public Operate(String str[]){        this.str = str;        if(str.length!=2){            System.out.println("输入的参数不正确");            System.exit(1);            //JVM运行终止,设置一个非0的参数即可        }    }        //用户再次输入    public static void inputTest(){                        System.out.println("请再次输入用户名和密码");                                String str[] = new String[2];            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));                        for (int i = 0; i < str.length; i++) {                try {                    str[i] = br.readLine();                } catch (IOException e) {                    // TODO Auto-generated catch block                    e.printStackTrace();                }            }                                }        public boolean getInfo(){        if(new LoginEntity(this.str[0], this.str[1]).validate()){            return true;        }else{            return false;        }    }}


Login
Java code
package mystudy.j2se.DemoLogin02;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;public class Login {    public static void main(String[] args) {                System.out.println("请输入用户名和密码");                String str[] = new String[2];        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));                for (int i = 0; i < str.length; i++) {            try {                str[i] = br.readLine();            } catch (IOException e) {                // TODO Auto-generated catch block                e.printStackTrace();            }        }                        Operate o = new Operate(str);                if(!o.getInfo()){            System.out.println("登录失败");                        o.inputTest();                    }else{            System.out.println("登陆成功");        }            }        }


谢谢大家指点, 看看有木有 更简单的

[解决办法]
public boolean validate(){
if(name.equals("abc")&&password.equals("123")){
return true;
}else{
return false;
}

 }
 public boolean getInfo(){
if(new LoginEntity(this.str[0], this.str[1]).validate()){
return true;
}else{
return false;
}
 }
这两处的判断有点像画蛇添足。
直接return name.equals("abc")&&password.equals("123");
return new LoginEntity(this.str[0], this.str[1]).validate();
------解决方案--------------------


package study19.Account;

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class AccountDemo {

public static void main(String[] args) {
AccountManager manager = new AccountManager();
Scanner console = new Scanner(System.in);
while(true){
showMenu();
String cmd = console.nextLine().trim();
if("0".equals(cmd)){
System.out.println("下次见!");
break;
}else if("1".equals(cmd)){
System.out.println
("输入你的注册信息格式是:邮箱 密码,如:tom@gamil.com 123456");
String someuser = console.nextLine();
someuser.matches
("^\\s*\\w+(?:\\.{0,1}[\\w-]+)*@[a-zA-Z0-9]+" +
"(?:[-.][a-zA-Z0-9]+)*\\.[a-zA-Z]+\\s*$" );
String[] data = someuser.split("\\s+");
try{
User user = manager.reg(data[0], data[1]);
System.out.println("注册成功:"+user);
}catch(EmailExistException e){
System.out.println(e.getMessage());
}catch(Pwd2ShortException e){
System.out.println(e.getMessage());
}catch(ArrayIndexOutOfBoundsException e){
System.out.println(e.getMessage());
}

}else if("2".equals(cmd)){
System.out.println
("输入你的登录,信息格式是:邮箱 密码,如:tom@gamil.com 123456");
String someuser = console.nextLine();
//匹配邮箱正则表达

someuser.matches
("^\\s*\\w+*@[a-zA-Z0-9]+" +
"(\\.[a-zA-Z0-9]+)*\\.[a-zA-Z]+\\s*$" );
String[] data = someuser.split("\\s+");
try{
User user = manager.login(data[0], data[1]);
System.out.println("登录成功!"+user);
}catch(EmailOrPwdException e){
System.out.println(e.getMessage());
}catch(ArrayIndexOutOfBoundsException e){
e.printStackTrace();
}

}else
System.out.println("命令错误!");

}
}
public static void showMenu(){
System.out.println("欢迎使用,请输入你的选择:");
System.out.println("***********************");
System.out.println("1:注册帐号");
System.out.println("2:登录帐号");
System.out.println("0:退出");
}

}
//帐号管理
class AccountManager{
private Map<String, User> users= 
new HashMap<String, User>();
private int id = 1;
//用邮箱注册
public User reg(String email,String pwd) 
throws EmailExistException,Pwd2ShortException{//异常的使用
if(pwd == null || pwd.length()<6){
throw new Pwd2ShortException("密码太短了!");
}
if(users.containsKey(email)){
throw new EmailExistException("用户已经存在!");
}
User someone = new User(id++, email, pwd);
users.put(email, someone);
return someone;

}
//登录
public User login(String email,String pwd) 
throws EmailOrPwdException{
User one = users.get(email);
if(one == null)
System.out.println("查无此人!");
if(one.getPwd().equals(pwd))
return one;
throw new EmailOrPwdException("密码错误!");


}

class User{
private int id;
private String email;
private String pwd;
public User() {
// TODO Auto-generated constructor stub
}
public User(int id, String email, String pwd) {
super();
this.id = id;
this.email = email;
this.pwd = pwd;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {


this.pwd = pwd;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
User other = (User) obj;
if (id != other.id)
return false;
return true;
}
@Override
public String toString() {
return "User [email=" + email + ", id=" + id + "]";
}


}
/**自定义异常必须继承于Exception
 * 手动继承所有父类构造器
 * */
class EmailExistException extends Exception{

public EmailExistException() {
super();
// TODO Auto-generated constructor stub
}

public EmailExistException(String message, Throwable cause) {
super(message, cause);
// TODO Auto-generated constructor stub
}

public EmailExistException(String message) {
super(message);
// TODO Auto-generated constructor stub
}

public EmailExistException(Throwable cause) {
super(cause);
// TODO Auto-generated constructor stub
}


}
class Pwd2ShortException extends Exception{


public Pwd2ShortException() {
super();
}


public Pwd2ShortException(String message, Throwable cause) {
super(message, cause);

}

public Pwd2ShortException(String message) {
super(message);

}


public Pwd2ShortException(Throwable cause) {
super(cause);

}

}
class EmailOrPwdException extends Exception{



public EmailOrPwdException() {
super();
// TODO Auto-generated constructor stub
}

public EmailOrPwdException(String message, Throwable cause) {
super(message, cause);
// TODO Auto-generated constructor stub
}

public EmailOrPwdException(String message) {
super(message);
// TODO Auto-generated constructor stub
}

public EmailOrPwdException(Throwable cause) {
super(cause);
// TODO Auto-generated constructor stub
}

}





[解决办法]
最简单这样:
1,验证用户名密码是否正确,如果错误,直接关闭程序,关闭前告诉他,不嫌麻烦就继续输入错误吧;
2,这样程序就很简单了,保证一次成功;

哈哈。。。。。。。。。。。。。
[解决办法]
如果你仅仅是为了求代码最简化,为啥还要搞出3个类?

Java code
    public static void main(String[] args) throws Exception {        Scanner sc = new Scanner(System.in);        while (true) {            System.out.print("UserName: ");            String name = sc.next();            System.out.print("Password: ");            String pass = sc.next();            if (name.equals("abc") && pass.equals("123"))break;            System.out.println("WRONG! Please input again.");        }        System.out.println("Welcome baby!");    } 

热点排行