0
import java.util.Scanner;

public class Cardhelp2{

private static String[] pairArray={"A,A","K,K","Q,Q","J,J","10,10","9,9","8,8","7,7","6,6","5,5","4,4","3,3","2,2"};

public static void generateRandom(int k){
 int minimum = 0;
 int maximum = 13;
 for(int i = 1; i <= k; i++)
   {
     int randomNum = minimum + (int)(Math.random()* maximum);
     System.out.print("Player " + i +" , You have been dealt a pair of: ");
     System.out.println(pairArray[randomNum]);
   }
} //reads array and randomizes cards

 public static void main(String[] args) {
 Scanner scan = new Scanner(System.in);
 System.out.print("How many players would you like to play with? ");
 int m = scan.nextInt();
 generateRandom(m);

//displays the cards

___________________________________________________
System.out.println("Would you like to play?");
 Scanner scanner = new Scanner(System.in);

 if(scanner.next().equalsIgnoreCase("y")||scanner.next().equalsIgnoreCase("yes")) {
System.out.println("This will be fun");
} else if(scanner.next().equalsIgnoreCase("n")||scanner.next().equalsIgnoreCase("no")) {
System.out.println("Maybe next time");
} else { 
System.out.println("Invalid character");

 }
 }
}

我无法理解为什么最后部分不起作用,我被告知我需要更改scanner.next(); 到一个变量,但我不知道如何去做并使代码工作。是否有一种简单的方法来阅读用户的答案然后向用户显示响应?

谢谢

4

3 回答 3

6

你的条件表达式

if(scanner.next().equalsIgnoreCase("y")||scanner.next().equalsIgnoreCase("yes")) 

调用scanner.next()两次,这意味着第二次调用将读取/等待更多输入。相反,您只需要调用一次,存储结果并在比较中使用它:

String tmp = scanner.next();
if(tmp.equalsIgnoreCase("y")||tmp.equalsIgnoreCase("yes")) 
于 2012-04-30T18:16:59.000 回答
1

让我们假设用户输入“是”。

if(scanner.next().equalsIgnoreCase("y")||scanner.next().equalsIgnoreCase("yes")) {

Scanner.next()在第一次测试中产生“是”。所以代码是有效的

"yes".equalsIgnoreCase("y")

这是错误的,所以它移动到下一个测试:

scanner.next().equalsIgnoreCase("yes")

这就是您的问题所在。

输入的“是”已经被第一次测试消耗掉了。现在扫描仪缓冲区中没有任何内容。

如果你想再次测试相同的输入,你必须捕获它,并在你的测试中使用它。

所以

String userReply= Scanner.next();
if(userReply.equalsIgnoreCase("y")||userReply.equalsIgnoreCase("yes")) {...

这是因为,每次调用 时scanner.next()Scanner都会返回流中的下一个值,然后MOVES PAST IT

如果用户输入“yes”然后输入“no”,测试将按如下方式执行:

if("yes".equalsIgnoreCase("y")||"no".equalsIgnoreCase("yes")) {...
于 2012-04-30T18:21:21.067 回答
0

你需要改变Scanner调用的方式。

用户输入似乎没有跟随下一个令牌\nScanner然后你需要逐行阅读。:

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.print("How many players would you like to play with? ");
    int m = Integer.parseInt(sc.nextLine()); // May thrown NumberFormatException
    generateRandom(m);

    //displays the cards

    System.out.print("Would you like to play? ");
    String input = sc.nextLine();

    if (input.equalsIgnoreCase("y") || input.equalsIgnoreCase("yes")) {
        System.out.println("This will be fun");
    } else if (input.equalsIgnoreCase("n") || input.equalsIgnoreCase("no")) {
        System.out.println("Maybe next time");
    } else {
        System.out.println("Invalid character");
    }
 }
于 2012-04-30T21:26:14.703 回答