我不能让Java接受键盘输入字符串

时间:2015-03-14 19:20:41

标签: java input

我想知道如何在我的java程序中使用键盘响应来正常工作并继续游戏。

我意识到代码有点乱,数组可能更适合,但对于这个实例,我只想答复键盘输入。

游戏运行良好,直到达到if和if else语句。然后我真的不知道如何解决它。

import java.util.Random;
import java.util.Scanner;

class blackjack {
    public static void main(String[] args) {
        Random r = new Random();

        Scanner keyboard = new Scanner(System.in);
        String money;
        String name;
        String hiscore;
        String h;
        String s;

        int card1 = 1 + r.nextInt(11);
        int card2 = 1 + r.nextInt(11);
        int card3 = 1 + r.nextInt(11);
        int card4 = 1 + r.nextInt(11);
        int card5 = 1 + r.nextInt(11);
        int card6 = 1 + r.nextInt(11);
        int card7 = 1 + r.nextInt(11);
        int card8 = 1 + r.nextInt(11);
        int card9 = 1 + r.nextInt(11);
        int card10 = 1 + r.nextInt(11);
        int card11 = 1 + r.nextInt(11);
        int card12 = 1 + r.nextInt(11);
        int card13 = 1 + r.nextInt(11);

        int total1 = card2 + card3;
        int total2 = total1 + card4;

        System.out.println("Welcome to Blackjack ! ");
        System.out.println("Score as close to 21 without going over to win ");
        System.out.println("What is your name?");
        name = keyboard.nextLine();
        System.out.println("Hello " + name);
        System.out.println("Let's play some BlackJack!");

        System.out.println("The dealer shows: \n\t\t" + card1);
        System.out.println("Your first card is: \n\t\t " + card2);
        System.out.println("Your second card is: \n\t\t" + card3);
        System.out.println("giving you a total of " + total1);
        System.out.println("Would you like to (H)it or (S)tick?");
        if h = keyboard.nextLine();
        System.out.println("Your next card is " + card4);
        System.out.println("Giving you a new total of: " + total2);
        if else s = keyboard.nextLine();
        System.out.println("your final score is: "total1);
    }
}

1 个答案:

答案 0 :(得分:0)

if(和if-else)语句 已损坏 。它的语法无效。正确的语法是:

if(h = keyboard.nextLine());

请注意,我说这是正确的语法,但这肯定不会按照您的意愿执行。看起来你想要做的就是检查预定的字符串" h"和" s"。

将变量存储在某处,然后进行比较。请记住,要比较Java中的字符串,您需要使用.equals()。

String response = keyboard.nextLine();
if("h".equals(response)) {
    // perform operations here
} else if("s".equals(response)) {
    // perform operations here
}