在java中的do while循环中跳过扫描程序输入

时间:2012-08-08 05:26:30

标签: java java.util.scanner do-while

我的作业有问题。该程序应首先运行registration()。如果用户未满13岁,则会发出提醒,并应返回registration()。如果用户超过13岁,它将运行displayProfile()并要求确认,如果答案是肯定的,它将通知它是成功的并且程序结束。如果答案为否,则应返回registration()并处理重复。如果答案无效,它应该继续提示有效答复。 问题出在registration()。在程序开始时,它工作正常,但当我输入一个13岁以下的用户并返回到注册时,它会跳过输入部分的姓氏,而是打印出“名字:” 。它是在while循环中,因为我想验证输入是否只是字符和空格。对于注册中的其他字段,一切正常。它只是在下一次运行时提示输入它不起作用的姓氏。算法出了什么问题?

import java.util.Calendar;
import java.util.Scanner;



public class mainExercise{
static Scanner input = new Scanner(System.in);
static String lastName;
static String firstName;
static String email;
static String gender;
static String bday;
static int birthMonth;
static int birthDay;
static int birthYear;
static String confirmation;

static EmailValidator ev = new EmailValidator();
static Calendar cal = Calendar.getInstance();

public static void main(String[] args){

    do{

        do{
            registration();
        }while(validateAge(birthMonth, birthDay, birthYear) != 1);

        displayProfile();

        do{
            confirmation = input.nextLine();
            }while(confirm(confirmation)== -1);

        if(confirm(confirmation)==0){
            break;
        }

    }while(confirm(confirmation)== 1);

    System.out.println("Thank you for registering, " + firstName);

}//end of main


static void registration(){

    System.out.println("Welcome to Old School Facebook");
    System.out.println("To register, please provide the following      information");               

    System.out.print("Last Name: ");
    do{ 
        lastName = input.nextLine();
        }while(validateName(lastName) != 1);

    System.out.print("First Name: ");
    do{
        firstName = input.nextLine();
        }while(validateName(firstName) != 1);

    System.out.print("Email: ");
    do{
        email = input.nextLine();
        }while(validateEmail(email) != 1);

    System.out.print("Gender: ");
    do{
        gender = input.nextLine();
        }while(validateGender(gender) != 1);

    System.out.println("Enter birthdate");
    do{
        System.out.print("Month: ");
        birthMonth = input.nextInt();
        }while(validateBirthInput(birthMonth) != 1);

    do{
        System.out.print("Day: ");
        birthDay = input.nextInt();
        }while(validateBirthInput(birthDay) != 1);

    do{
        System.out.print("Year: ");
        birthYear = input.nextInt();
        }while(validateBirthInput(birthYear) != 1);


}

static int validateName(String s){
    int valid = 1;
    char name[] = s.toCharArray();
    for(int i=0; i<name.length; i++){
        if(Character.isLetter(name[i]) || Character.isWhitespace(name[i])){
            valid = 1;
        }else{
            System.out.println("Invalid input");
            valid = 0;
            break;
        }
    }
    return valid;
}

static int validateEmail(String s){
    int valid = 1;
    if(ev.validate(s)){
        valid = 1;
    }else{
        System.out.println("Invalid email");
        valid = 0;
    }
    return valid;
}

static int validateGender(String s){
    int valid = 1;
    if(s.toLowerCase().compareTo("m") == 0 || s.toLowerCase().compareTo("f") == 0){
        valid = 1;
    }else{
        valid = 0;
    }
    return valid;
}

static int validateBirthInput(int x){
    int valid = 1;
    int birth;
    try{
        birth = x;
    }catch(Exception e){
        System.out.println("Enter numbers 1-12 for month, 1-31 for day, yyyy for year");
        valid = 0;
    }
    return valid;
}

static int validateAge(int bm, int bd, int by){
    int valid = 1;
    int cm = cal.get(Calendar.MONTH);
    int cd = cal.get(Calendar.DAY_OF_MONTH);
    int cy = cal.get(Calendar.YEAR);

    if((cy-by)<=13){
        if(bm>=cm){
            if(bd>cd){
                valid = 0;
                System.out.println("You must be at least 13 years old");
                System.out.println();
            }
        }
    }else{
        valid = 1;
    }
    return valid;
}

static int confirm(String s){
    int reply;
    if(s.toLowerCase().compareTo("yes") == 0){
        reply = 1;
    }else if(s.toLowerCase().compareTo("no") >0){
        reply = 0;
    }else{
        System.out.println("Invalid input. Type yes or no");
        reply = -1;
    }
    return reply;
}

static void displayProfile(){
    System.out.println();
    System.out.println("Last Name: " + lastName);
    System.out.println("First Name: " + firstName);
    System.out.println("Email: " + email);
    System.out.println("Gender: " + gender);
    System.out.printf("Birthday: %d/%d/%d\n\n", birthMonth, birthDay, birthYear);
    System.out.println("(yes or no): ");

}
}

2 个答案:

答案 0 :(得分:2)

嘿,这个非常棘手。

查看Scanner.nextInt()的javadoc:

  

将输入的下一个标记扫描为int

现在将其与Scanner.nextLine()的内容进行比较:

  

使此扫描程序超过当前行并返回跳过的输入。此方法返回当前行的其余部分,不包括末尾的任何行分隔符。该位置设置为下一行的开头。

因此,当您致电nextInt()时,您只能从输入中读取“int”,当您致电nextLine()时,您会一直读到该行的末尾。您的扫描仪正在从System.in读取,这有点奇怪之处在于,在您点击 之后,它不会向扫描仪提供任何数据无论你自己输入哪一行。当您要求日期/月/年时,用户输入一些数字,但在用户点击输入之前没有任何反应,然后您调用nextInt(),它会读取输入的数字。

到目前为止一直很好,除了扫描仪只读取用户键入的数字,而不是新行。因此,当您再次通过registration()方法时,扫描程序中会有一个备用空白行,lastName = input.nextLine();会立即读取该行,假定它有效,然后继续询问名字。

由于这是您的作业,请查看您正在阅读的内容以及用户输入的内容,请记住,在用户点击之前,System.in不会向扫描程序发送任何内容。 / KBD>。您可以查看此Integer method, parseInt(String),而不是使用nextInt()

答案 1 :(得分:0)

我改变了你的代码。您也可以根据自己的需要进行更改.. 快乐的编码.. :)

import java.util.Calendar;
import java.util.Scanner;

public class mainExercise{
static Scanner input = new Scanner(System.in);
static String lastName;
static String firstName;
static String email;
static String gender;
static String bday;
static int birthMonth;
static int birthDay;
static int birthYear;
static String confirmation;

//static EmailValidator ev = new EmailValidator();
static Calendar cal = Calendar.getInstance();

public static void main(String[] args){

    do{

        do{
            registration();
        }while(validateAge(birthMonth, birthDay, birthYear) != 1);

        displayProfile();
// this is coming "Invalid input. Type yes or no"  because ist time input.nextLine() return ("") thats why.
        do{
            confirmation = input.nextLine();
            }while(confirm(confirmation)== -1 || confirmation.equals(""));

        if(confirm(confirmation)==1){
            break;
        }

    }while(confirm(confirmation)== 1);

    System.out.println("Thank you for registering, " + firstName);

}//end of main


static void registration(){

    System.out.println("Welcome to Old School Facebook");
    System.out.println("To register, please provide the following      information");               

    System.out.print("Last Name: ");
    do{ 
        lastName = input.nextLine();
        }while(validateName(lastName) != 1);

    System.out.print("First Name: ");
    do{
        firstName = input.nextLine();
        }while(validateName(firstName) != 1);

    System.out.print("Email: ");
    do{
        email = input.nextLine();
        }while(validateEmail(email) != 1);

    System.out.print("Gender: ");
    do{
        gender = input.nextLine();
        }while(validateGender(gender) != 1);

    System.out.println("Enter birthdate");
    do{
        System.out.print("Month: ");
        birthMonth = input.nextInt();
        }while(validateBirthInput(birthMonth) != 1);

    do{
        System.out.print("Day: ");
        birthDay = input.nextInt();
        }while(validateBirthInput(birthDay) != 1);

    do{
        System.out.print("Year: ");
        birthYear = input.nextInt();
        }while(validateBirthInput(birthYear) != 1);


}

static int validateName(String s){
    int valid = 1;
    char name[] = s.toCharArray();
    for(int i=0; i<name.length; i++){
        if(Character.isLetter(name[i]) || Character.isWhitespace(name[i])){
            valid = 1;
        }else{
            System.out.println("Invalid input");
            valid = 0;
            break;
        }
    }
    return valid;
}

static int validateEmail(String s){
    int valid = 1;
    // this is showing error. You have to first initialize ev variable  .
    if(ev.validate(s)){
        valid = 1;
    }else{
        System.out.println("Invalid email");
        valid = 0;
    }
    return valid;
}

static int validateGender(String s){
    int valid = 1;
    // you have to check whith 1st char of that string othrewise it always show false
    if(s.toLowerCase().substring(0, 1).compareTo("m") == 0 || s.toLowerCase().substring(0, 1).compareTo("f") == 0){
        valid = 1;
    }else{
        valid = 0;
    }
    return valid;
}

static int validateBirthInput(int x){
    int valid = 1;
    int birth;
    try{
        birth = x;
    }catch(Exception e){
        System.out.println("Enter numbers 1-12 for month, 1-31 for day, yyyy for year");
        valid = 0;
    }
    return valid;
}

static int validateAge(int bm, int bd, int by){
    int valid = 1;
    int cm = cal.get(Calendar.MONTH);
    int cd = cal.get(Calendar.DAY_OF_MONTH);
    int cy = cal.get(Calendar.YEAR);
// this should also need to change like following 
      if ((cy - by) > 13)
      {
         return valid;
      }
      else if ((cy - by) == 13)
      {
         if (bm>cm)
         {
            return valid; 
         }
         else if (bm==cm && bd>cd ) {
            return valid;
         }
      }
      System.out.println("You must be at least 13 years old");
      System.out.println();
      return 0;

}

static int confirm(String s){
    int reply;
    if(s.toLowerCase().compareTo("yes") == 0){
        reply = 1;
    }else if(s.toLowerCase().compareTo("no") >0){
        reply = 0;
    }else{
        System.out.println("Invalid input. Type yes or no");
        reply = -1;
    }
    return reply;
}

static void displayProfile(){
    System.out.println();
    System.out.println("Last Name: " + lastName);
    System.out.println("First Name: " + firstName);
    System.out.println("Email: " + email);
    System.out.println("Gender: " + gender);
    System.out.printf("Birthday: %d/%d/%d\n\n", birthMonth, birthDay, birthYear);
    System.out.println("(yes or no): ");

}
}