我不知道如何使用while循环来确保只有正确的名称才能跳出while循环

时间:2019-11-11 07:21:08

标签: java arrays while-loop

基本上,我的程序要求用户输入新名称,程序将检查新名称是否符合所有要求。

是的,名称应添加到数组中并打印在外部文件中。 如果不是,则应要求用户输入新名称。

我的问题是,我不怎么使用while循环来确保只有名称可以跳出循环。

我也在主要方法上签名我的问题

public static void main(String[] args)throws FileNotFoundException {
    readFile();
    listUserName();
    while() {          // my question is at here that I don't how to use while loop to make 
                          //sure that only the name which pass all the check..method can 
                          //jump out of the loop
inputNewName();
            checkduplicate();
            checklength();
            checkcase();
            checkstart();
            checknumber();
            checkspecial(); 
        }
        addNewName();
        listUserName();


    }
    public static void readFile()throws FileNotFoundException {
     //read file and reseve in array
        Scanner input = new Scanner(new File("users.txt"));
        int i=0;
        while(input.hasNext()) {
               String info=input.next();
               userName[i]=info;
               i++;
        }
    }
    public static void listUserName() {//print name
        for(int i=0;i<userName.length;i++) {
            System.out.println(userName[i]);
        }       
    }
    public static void inputNewName() {// prompt uder for a new name
        System.out.println("Create a new user:");
        Scanner console=new Scanner(System.in);
        newname=console.next();
    }
    public static void addNewName()throws FileNotFoundException {//add new name in array

       System.out.println("User: \""+newname+"\" added successfully!");
       System.out.println("List of usernames: ");

       String[] tempuser=new String[userName.length+1]; 
        for(int i=0;i<(userName.length+1);i++) {
            if(i<userName.length) {
                tempuser[i]=userName[i];

            }else if(i==userName.length) {
                tempuser[userName.length] =newname;
            }
            System.out.println(tempuser[i]);
            }
            userName=tempuser;
            PrintStream out=new PrintStream(new File("users.txt"));  
            for(int i=0;i<userName.length;i++) {
                out.println(userName[i]);
            }
 }   
    public static void checkduplicate() { //check duplicate

        for(int i=0;i<userName.length;i++) {    
            if(newname.equals(userName[i])) {
                System.out.println("Invalid Name.Name already in use.");    
               }else {
                   valid=true;
               }
        }
    }
    public static void checklength() {//check length
            if(newname.length()>7) {
                System.out.println("Invalid Name"+"\n"+"Name too long.");
                }
            if(newname.length()<4) {
                System.out.println("Invalid Name"+"\n"+"Name too short.");
                }
    }
    public static void checkcase() {//check case                            
            boolean upcase=false;
            boolean lowcase=false;
            for(int i=0;i<newname.length();i++) {

                    if((0+newname.charAt(i))>=65&&(0+newname.charAt(i)<=90)) {
                        upcase=true;
                    }else if((0+newname.charAt(i))>=97&&(0+newname.charAt(i))<=122) {
                        lowcase=true;
                    }
            }
            if(upcase==false||lowcase==false) {
                System.out.println("Usernames must have lower-case and upper-case");
            }
    }   
    public static void checkstart() {
        if(((0+newname.charAt(0))<65&&(0+newname.charAt(0)>99))||
                ((0+newname.charAt(0))<97&&(0+newname.charAt(0))>122)){

                System.out.println("Invalid name. Name must start with a letter");
            }       
    }
    public static void checknumber() {
        boolean check=false;
        for(int i=0;i<newname.length();i++) {
            if((0+newname.charAt(i))>=48&&(0+newname.charAt(i))<=57) {
                check=true;
            }
        }
        if(check!=true) {
            System.out.println("Username must have at least one number");
            }
    }
    public static void checkspecial() {
        boolean check=false;
            for(int i=0;i<newname.length();i++) {
                if((0+newname.charAt(i))==33||(0+newname.charAt(i))==35||(0+newname.charAt(i))==63) {
                    check=true;
                }
            }
            if(check!=true) {
                System.out.println("Username must have at least one special character.");   
            }
    }

}

2 个答案:

答案 0 :(得分:0)

一种优雅的解决方案是使您的方法为boolean类型,而不是void类型。然后,你可以做

boolean light;

do{
    light = true;
    if(!inputNewName()) light=false;
    if(!checkduplicate()) light=false;
    if(!checklength()) light = false;
    if(!checkcase()) light = false;
    if(!checkstart()) light = false;
    if(!checknumber()) light = false;
    if(!checkspecial()) light = false; 
}while(light==false);

请注意,我将每个方法放在不同的if语句中。这迫使代码到达所有方法。如果在只有一个方法失败的情况下确实不需要调用每个方法,则可以将它们组合在单个if语句中,或者实际上是在while条件下。

while(!inputNewName() || !checkduplicate() || !checklength() || !checkcase() || !checkstart() || !checknumber() || !checkspecial()) {}

此外,如果您将boolean变量创建为类的成员,然后在需要时在每个void方法中将其设置为false,则可以实现相同的结果-尽管我必须建议您不要这样做,即使这样做从设计的角度来看,这是糟糕的代码。

老实说,我要做的是:

  • 根据方法的概念区分方法。您这里有输入字符串,检查重复项和检查格式的方法。我将创建一个包含所有称为“ checkFormat()”的格式检查的方法。

  • 然后,正如我所说的,我将使每个布尔类型的方法都成为可能。

我的时间是:

boolean light;
do
{
    light = inputNewName();
    if(light) light = checkDuplicate(); //this D should be upper case to follow the camel-case convention.
    if(light) light = checkFormat();
} while (!light); 

更新:我刚刚意识到您的代码旨在使用我告诉您不要使用的技术。您可以随时使用一个名为“ valid”的变量。 尽管我真的建议您不要这样做,但您可以继续进行以下操作:

do{
    //all your stuff
} while(!valid);

答案 1 :(得分:0)

在您的情况下,您可能宁愿使用do ... while循环(它与while循环完全相同,只是保证可以运行一次。实际上,您希望在{之间运行代码{1}}和do {,直到达到特定条件(在您的时间段中定义)为止。

因此,在您的实现中,您将在输入} while(condition)无效的情况下运行while循环,其外观类似于以下内容:

string

请注意,checkLength方法返回一个public class WhileLoop { public WhileLoop() {} public void run() { String name; boolean isValid; do { isValid = Boolean.FALSE; // We want to set this to FALSE on each run of the loop. System.out.println("Create a new user:"); Scanner console = new Scanner(System.in); name = console.next(); isValid = isValid || checklength(name); // run the checkLength method and perform a logical OR on the result from the method } while (!isValid); // loop while isValid = FALSE (Not TRUE) System.out.println("Name: " + name); } public boolean checklength(String name) { //check length, return TRUE if valid, else FALSE. boolean isVaild = Boolean.TRUE; // Set the default return value to FALSE if(name.length() > 7) { System.out.println("Invalid Name" + System.lineSeparator() + "Name too long."); isVaild = Boolean.FALSE; // If not valid then set isVaild to FALSE } return isVaild; } public static void main (String ... args) { WhileLoop whileLoop = new WhileLoop(); whileLoop.run(); } } ,其结果使用逻辑OR应用于您的标志。

现在,您只需添加以下各种检查:

boolean

哦,关于良好实践的一小部分:

  • 在打印换行符时,请使用isValid = isValid || checklength(name); isValid = isValid || checkCase(name); ... isValid = isValid || checkStart(name); 而不是System.lineSeparator()
  • 而不是使用逻辑或(\n),请按如下所示使用布尔函数:

    ||

相关问题