为什么什至以为输入为0时我的第一个输入都会通过do执行

时间:2019-02-27 01:24:26

标签: java

我正在做一个有关Casino App的学校计划。首先没关系,但是后来我发现我的第一个输入出了点问题。奇怪的是,只有第一个输入出错了,其他的都没问题。我想知道发生这种情况的原因是什么?

public class test1
{   

public static Scanner input;

public static void main(String[] args) 
{
    int winnings;
    int bet = getBet();

    do
    {   
    TripleString thePull = pull();
    getPayMultiplier(thePull);
    winnings = bet * getPayMultiplier(thePull);
    display(thePull, winnings);
    bet =getBet();
    }

    while(bet != 0);
        System.out.print("Thank you!");
}





public static int getBet()
{
    final double MAX_BET = 50;
    final double MIN_BET = 0 ;
    String prompt, userResponse;
    int Response;

    do
    {
        prompt = "How much would you like to bet (1 - 50) or 0 to quit?";
        System.out.print(prompt);
        userResponse = input.nextLine();
        Response = Integer.parseInt(userResponse);
    }
    while (Response < MIN_BET || Response > MAX_BET);

    return Response;
}

我的问题是,当我将第一个输入设为0(bet!= 0)时,它显示:

How much would you like to bet (1 - 50) or 0 to 
quit? 0
whirrrrrr .... and your pull is ...
BAR BAR BAR
Sorry, you lose.

How much would you like to bet (1 - 50) or 0 to 
quit?

这是错误的。它应该立即退出,但是如果我在第一个输入之外的任何地方都输入0,它将起作用:

How much would you like to bet (1 - 50) or 0 to 

quit? 1
whirrrrrr .... and your pull is ...
7 BAR cherries
Sorry, you lose.

How much would you like to bet (1 - 50) or 0 to quit? 0
Thanks for coming to Casino Loceff

那是为什么?

4 个答案:

答案 0 :(得分:0)

因为do-while循环将在循环中至少运行一次,并且仅在最后检查中断条件。如果您不希望该行为切换为正常的while循环。

while(condition) { // your statements }

答案 1 :(得分:0)

因为响应为0。而且它不小于MIN_BET(为0),所以循环不会重复。

将其更改为<= MIN_BET,或者(可能更好)将MIN_BET更改为1。

答案 2 :(得分:0)

问题是使用do-while循环。做一遍的目的是确保代码块总是至少执行一次

正则whiledo-while之间的区别在于计算表达式时。

在常规while循环中,在每个循环开始之前检查表达式。 “我应该运行代码吗?”。这意味着,如果表达式为假,它将永远不会运行该块。

在使用do-while的情况下,在代码块执行后 检查表达式-“我是否应该再次执行此操作?”。因此,即使表达式为假,代码块也会在第一次执行。

尝试使用常规的while循环而不是do-while

https://docs.oracle.com/javase/tutorial/java/nutsandbolts/while.html

答案 3 :(得分:0)

您的问题很可能在这里

public static int getBet()
{
    final double MAX_BET = 50;
    final double MIN_BET = 1;//this should be 1 since you're asking for users to enter 1-50
    String prompt, userResponse;
    int Response;

    do
    {
        prompt = "How much would you like to bet (1 - 50) or 0 to quit?";
        System.out.print(prompt);
        userResponse = input.nextLine();
        Response = Integer.parseInt(userResponse);

        //simplest way is just to add a condition here with an if statement to break the loop if the user enters 0
       if(userResponse == 0){
           break;
       }

    }
    while (Response >= MIN_BET && Response <= MAX_BET);

    return Response;
    }