2016-08-24 67 views
0

我刚开始使用Java,想要修改语法。每当我输入“F”到genderage大于或等于20时,如果用户结婚或者没有结婚,出于某种原因扫描仪正在跳过它,应该提示输入。其他一切正常。扫描仪跳过输入,可能的空白?

输出我得到:

Whats is your gender (M or F): F 
First name: Kim 
Last name: Kardashian 
Age: 32 

Are you married, Kim (Y or N)? 
Then I shall call you Ms. Kardashian. 

代码:

import java.util.Scanner; 

public class GenderGame 
{ 

    public static void main(String[] args) 
    { 
     Scanner sc = new Scanner(System.in); 

     int age = 0; 
     String Gender = null, fName = null, lName = null, M = null, type = null; 

     System.out.print("Whats is your gender (M or F): "); 
     Gender = sc.nextLine(); 
     Gender = Gender.toUpperCase(); 

     System.out.print("First name: "); 
     fName = sc.nextLine(); 

     System.out.print("Last name: "); 
     lName = sc.nextLine(); 

     System.out.print("Age: "); 
     age = sc.nextInt(); 

     if(Gender.equals("F") && age >= 20) 
     { 
      System.out.print("\nAre you married, " + fName + " (Y or N)? "); 
      M = sc.nextLine(); 
      M = M.toUpperCase(); 

      if(M.equals("Y")) 
      { 
       type = "Mrs. "; 
       type = type.concat(lName); 
      } 
      else 
      { 
       type = "Ms. "; 
       type = type.concat(lName); 
      } 
     } 
     else if(Gender.equals("F") && age < 20) 
     { 
      type = fName.concat(" " + lName); 
     } 
     else if(Gender.equals("M") && age >= 20) 
     { 
      type = "Mr. "; 
      type = type.concat(lName); 
     } 
     else if(Gender.equals("M") && age < 20) 
     { 
      type = fName.concat(" " + lName); 
     } 
     else 
     { 
      System.out.println("There was incorrect input. EXITING PROGRAM"); 
      System.exit(1); 
     } 

     System.out.println("\nThen I shall call you " +type+ "."); 

    } 

} 

回答

1

ScannernextInt()法叶新线的性格,那就是,它不消耗它。这个换行符被你的nextLine()方法消耗,这就是为什么你没有看到它等待你的输入。

为避免这种情况,请在age = sc.nextInt();之后拨打sc.nextLine(),然后保持其余代码不变。

 ... 
     System.out.print("Age: "); 
     age = sc.nextInt(); 
     sc.nextLine(); //added 

     if(Gender.equals("F") && age >= 20) 
     { 
      System.out.print("\nAre you married, " + fName + " (Y or N)? "); 
      M = sc.nextLine(); 
      M = M.toUpperCase(); 

      if(M.equals("Y")) 
      { 
       type = "Mrs. "; 
       type = type.concat(lName); 
      } 
     ...