2013-11-21 77 views
0

每當我運行這個代碼,它的工作非常順利,直到while循環運行一次。它將返回並再次詢問名稱,然後跳過String b = sc.nextLine();,然後打印下一行。我得到資源泄漏

static Scanner sc = new Scanner(System.in); 

static public void main(String [] argv) { 
    Name(); 
} 

static public void Name() { 

boolean again = false; 
do 
{ 
    System.out.println("What is your name?"); 

    String b = sc.nextLine(); 
    System.out.println("Ah, so your name is " + b +"?\n" + 
      "(y//n)"); 
    int a = getYN(); 
    System.out.println(a + "! Good."); 
    again = askQuestion(); 
} while(again); 



} 

static public boolean askQuestion() { 
    System.out.println("Do you want to try again?"); 
    int answer = sc.nextInt(); 

    if (answer == 1) { 
     return true; 
    } 
    else { 
     return false; 
    } 

} 

static int getYN() { 
    switch (sc.nextLine().substring(0, 1).toLowerCase()) { 
    case "y": 
     return 1; 
    case "n": 
     return 0; 
    default: 
     return 2; 
    } 
} 

}

另外,我想在某種程度上,我可以問三個問題來創建這個程序(如某人的姓名,性別和年齡,也許更像是種族和諸如此類的東西),和然後將所有這些答案帶回。就像最後說的那樣,「所以,你的名字是+名字+,你是+性別+,並且你年齡+歲以上?是/否。」沿着這些線的東西。我知道有一種方法可以實現,但我不知道如何將這些響應保存在任何地方,而且我不能抓住它們,因爲它們只發生在方法實例中。

回答

0

不要嘗試用nextLine()掃描文本在使用nextInt()後使用相同的掃描儀!它可能會導致問題。打開掃描儀方法僅適用於整數...推薦。 你總是可以解析掃描器的字符串答案。

此外,使用掃描儀這樣是不是一個好的做法,你可以組織問題在數組中選擇一個循環讀取一個獨特的掃描實例是這樣的:在全局變量

public class a { 

    private static String InputName; 
    private static String Sex; 
    private static String Age; 
    private static String input; 
    static Scanner sc ; 

    static public void main(String [] argv) { 
     Name(); 
    } 

    static public void Name() { 

     sc = new Scanner(System.in); 

     String[] questions = {"Name?","Age","Sex?"};// 
     int a = 0; 
     System.out.println(questions[a]); 

     while (sc.hasNext()) { 
      input = sc.next(); 
      setVariable(a, input); 
      if(input.equalsIgnoreCase("no")){ 
       sc.close(); 
       break; 
      } 
      else if(a>questions.length -1) 
      { 
       a = 0; 
      } 
      else{ 
       a++; 
      } 
      if(a>questions.length -1){ 
       System.out.println("Fine " + InputName 
         + " so you are " + Age + " years old and " + Sex + "."); 
       Age = null; 
       Sex = null; 
       InputName = null; 
       System.out.println("Loop again?"); 

       } 
       if(!input.equalsIgnoreCase("no") && a<questions.length){ 
       System.out.println(questions[a]); 
       } 
     } 

    } 


    static void setVariable(int a, String Field) { 
     switch (a) { 
     case 0: 
      InputName = Field; 
      return; 
     case 1: 
      Age = Field; 
      return; 
     case 2: 
      Sex = Field; 
      return; 
     } 
    } 
} 

注意的是,至極存儲您的信息,直到您將它們設置爲空或空...您可以使用它們進行最終的確認。

希望這會有所幫助! 希望這有助於!

+0

對不起,花了這麼長時間回到這個,但是,這有幫助!我知道了! –