2016-01-13 172 views
0

我有这个方法的问题。对于初学者来说,它会继续告诉我需要添加回报,我会在if else检查中添加回报。第二个问题是,根本不会循环。当我在if else语句之后添加一个返回值来测试循环(删除add返回错误)时,无论用户输入什么,它都会简单地遍历它。任何建议,将不胜感激。虽然循环如果其他语句不能正常工作

public static boolean newGame() { 

    // char variables for the user input 
    char yes = 'y'; 
    char no = 'n'; 

    // Request for user input 
    Scanner userInput = new Scanner(System.in); 
    System.out.println("Are you ready to play? Press \"y\" for Yes and \"n\" for No."); 

    // converts userInput to a char 
    String userChoice = userInput.nextLine(); 
    char userChar = userChoice.charAt(0); 

    do { 
    // determines if the game starts or not 
     if (userChar == yes) { 
      System.out.println("GREAT!! Let's play!"); 
      return true; 
     } else if (userChar == no) { 
      System.out.println("Thanks for playing!!"); 
      return false; 
     } else { 
      System.out.println("Please enter \"y\" or \"n\""); 
     } 
    } while (userChar != yes || userChar != no); 
} 
+1

循环是无限的,因为userChar在循环内部永远不会改变,如果你使它成为布尔值,你必须返回一个布尔值。 – ivan

+0

在||中使用.equals和&&它总是真的 – Ctx

+0

@Ctx'=='和'!='将在这里工作;值是'char'。 – rgettman

回答

4

对于初学者来说,它仍然告诉我,我需要添加一个回报,我将在其他如果检查返回。

Java将不计算循环,以确定它在逻辑上只能从循环中返回truefalse,而不是跳出循环的喜欢,我们可以看到。

既然你永远不想超越这个循环的方法,只是为了满足编译器,如果代码碰巧得到那么远(它不会),它会抛出一个IllegalStateException

// end of while loop 
throw new IllegalStateException("Didn't expect to make it to this point!"); 

它只是通过它运行一次,无论什么样的用户输入。

它始终是一个char不是'y'它不是'n'的情况。你要确保它不是在再次循环之前,使用&&运算符(“和”)。如果字符不是'y',则保持循环它不是'n'

} while (userChar != yes && userChar != no); 

此外,作为另一位用户刚指出,把你输入的循环中,让你再次询问用户是否是没有预料到的输入的字符。

0

您需要在循环中输入内容,以便获得新的输入。

public static boolean newGame() { 

    // char variables for the user input 
    char yes = 'y'; 
    char no = 'n'; 

    // Request for user input 
    Scanner userInput = new Scanner(System.in); 
    System.out.println("Are you ready to play? Press \"y\" for Yes and \"n\" for No."); 


    do { 
     // converts userInput to a char 
     String userChoice = userInput.nextLine(); 
     char userChar = userChoice.charAt(0); 
    // determines if the game starts or not 
     if (userChar == yes) { 
      System.out.println("GREAT!! Let's play!"); 
      return true; 
     } else if (userChar == no) { 
      System.out.println("Thanks for playing!!"); 
      return false; 
     } else { 
      System.out.println("Please enter \"y\" or \"n\""); 
     } 
    } while (userChar != yes && userChar != no); 
}