首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >我无法让Java接受键盘输入字符串

我无法让Java接受键盘输入字符串
EN

Stack Overflow用户
提问于 2015-03-15 03:20:41
回答 1查看 356关注 0票数 0

我想知道如何让我的java程序中的键盘响应正常工作,并照常继续游戏。

我知道代码有点凌乱,数组可能更适合,但在这个例子中,我只想要关于键盘输入的答案。

在到达if和if else语句之前,游戏运行得足够好。那我就真的不知道该怎么修了。

代码语言:javascript
复制
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);
    }
}
EN

回答 1

Stack Overflow用户

发布于 2015-06-20 06:52:01

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

代码语言:javascript
复制
if(h = keyboard.nextLine());

请注意,我说过这是正确的语法,但这肯定不会做您想要它做的事情。看起来你想要做的是对照预定的字符串"h“和"s”进行检查。

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

代码语言:javascript
复制
String response = keyboard.nextLine();
if("h".equals(response)) {
    // perform operations here
} else if("s".equals(response)) {
    // perform operations here
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29053161

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档