有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

我对这个作业有意见。程序应该首先运行registration()。如果用户未满13岁,它将发出警报,并应返回registration()。如果用户超过13岁,它将运行displayProfile()并请求确认,如果回答是“是”,它将通知成功,程序结束。如果答案是否定的,它应该返回到registration()并重复该过程。如果答案是无效的,它应该继续提示一个有效的答复。 问题出在registration()。在程序开始时,它工作正常,但当我输入一个13岁以下的用户并返回注册时,它会跳过姓氏的输入部分,而是继续打印“First name:”。它位于do-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) 个答案

  1. # 1 楼答案

    我更改了你的密码。您也可以根据自己的情况进行更改。。 快乐编码…)

    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): ");
    
    }
    }
    
  2. # 2 楼答案

    嘿,这个很棘手

    请看一下Scanner.nextInt()的javadocs:

    Scans the next token of the input as an int

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

    Advances this scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line.

    因此,当您调用nextInt()时,您只从输入中读取一个“int”,当您调用nextLine()时,您一直读取到行尾。您的扫描仪正在从System.in读取数据,这有点奇怪,因为它不会向扫描仪提供任何数据,直到您点击回车,将您键入的内容自动放入一行。当您要求输入日期/月/年时,用户键入一些数字,但直到用户点击enter,然后您调用^{,它才会读取键入的数字

    到目前为止还不错,只是扫描仪只读取用户键入的数字,而不是新行。因此,当您再次使用registration()方法时,扫描器中有一个备用的空行,lastName = input.nextLine();会立即读取它,假设它是有效的,然后继续询问名字

    因为这是你的家庭作业,所以看看你在读什么,用户在输入什么,记住这个系统。在中,在用户点击enter之前,不会将任何内容交给扫描仪。您也许可以看看这个Integer method, parseInt(String),而不是使用nextInt()