扫描仪不会等待新输入

时间:2015-11-01 23:36:45

标签: java arrays arraylist java.util.scanner

我有一个程序按预期工作,除了它的一个重要方面。

每次按下输入按钮时,程序应该从标准牌组中取出一张随机牌。

截至目前,当我按下Enter键时,我可以让程序给我一张随机卡片,但我不能让它一次只能工作一张。按下输入一次后,我的控制台将所有52张卡片填入其中。

在交易下一张卡之前,我怎样才能让它等待我按下回车键? (卡片处理功能是接近结束的while循环)

import java.util.Arrays;
import java.util.Scanner;
import java.util.Random;
import java.util.ArrayList;

public class Card {

      public static void main(String[] args) {
              String[] suit = {" of Diamonds", " of Spades", " of Hearts", " of Clubs"}; //Array of suits
              String[] faces = {"Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"};//Array of face values
              String[] deck = new String[52];//Array of actual deck
              int[] random = new int[52]; //Array with all possible numbers between 1-52
              boolean deckComplete = false;//Boolean for finished deck

              for (int x = 0; x<random.length; x++) {
                      random[x] = x;
              } //Fills array with all possible numbers between 1-52

              Random rndNum = new Random();

              Scanner scanner = new Scanner(System.in);
              String readString = scanner.nextLine();

              for (int i = 0; i < deck.length; i++) {
                      deck[i] = faces[i % 13] + suit[i/13];
              } //Creates array with all possible cards in standard deck of cards

              ArrayList<String> arrayList = new ArrayList<String>(Arrays.asList(deck)); //Converts above array into ArrayList


              while (deckComplete == false) {
                      for (int i = 52; i >= 1; i--) {
                              int randomNumber = rndNum.nextInt(i);
                              if (readString.equals("")) {
                                      System.out.println(arrayList.get(random[randomNumber]));
                                      arrayList.remove(random[randomNumber]);
                                      if (i == 1) {
                                              deckComplete = true;
                                      } //Deals out random card from deck and removes each one used
                              }
                      }

              }
      }
}

1 个答案:

答案 0 :(得分:2)

你的程序只做你告诉它做的事,不多也不少。从逻辑上思考一下你的思想中的代码 - 你会看到scanner.nextLine()只被调用一次,才能在 for循环之前,因此你的程序将等待输入<强大>只有一次,就像写的一样。相反,如果你想在处理每张卡之前等待输入,那么代码行需要在for循环中被称为 。现在再次只调用一行代码。