2013-11-21 76 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

对不起,花了这么长时间回到这个,但是,这有帮助!我知道了! –