首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >java:仅带开关的循环有时会起作用

java:仅带开关的循环有时会起作用
EN

Stack Overflow用户
提问于 2018-10-15 06:24:00
回答 1查看 52关注 0票数 0

在这件事上我真的抓狂了。我是新来爪哇的,我正在经历最奇怪的事情。

这是家庭作业,我一步一步来做。我的问题是,循环只是继续运行,并停止请求输入,一直循环,直到它终止。我的评论主要是针对我自己的。我试图提取导致我的问题的原因,并将其发布在这里。

看看"hatColor“开关,你会注意到我是如何确保用户只从我分配的选项中输入的。我是否应该使用异常处理程序或其他什么?

总之,简而言之,问题是如果我输入一些带有空格的东西,循环会跳过询问我的下一个输入。例如,如果我在第一次提示时在扫描仪中输入"y“,程序将终止,并且不给我输入其他内容的机会。

请理解这一点的任何人,我将非常感谢您的帮助。

import java.util.Scanner;

public class Testing
{
    static String hatColor;
    public static void main(String[] args) {
    gameStart();    
    }

public static void gameStart() 
{       
    Scanner userInput = new Scanner(System.in);
    boolean keepLooping = true;
    int loopCounter = 0;

    System.out.println("The game begins. You must choose between 3 different colored hats."
            + " You can type white, black, or gray.");

    while (keepLooping == true) 

    {
        hatColor = userInput.next();
        switch(hatColor)
        {
        case "white":
            System.out.println("You have chosen the path of well intentioned decisions.");
            walletDrop();
            //the two items below are only there in case the wallet drop somehow completes without calling another method
            keepLooping = false; // stops the while loop from looping again.
            break; // breaks out of the  switch
        case "gray": 
            System.out.println("You have chosen the path of free will.");
            walletDrop();
            keepLooping = false;
            break;
        case "black" :
            System.out.println("You have chosen the path of personal gain.");
            walletDrop();
            keepLooping = false;
            break;
        default : //we could just copy this default chunk for later switch statements
            if (loopCounter >= 3)//end program on them
            {
                System.exit(0);
            }
            System.out.println("You didn't enter a usable answer. Try again");
            loopCounter++;
            if (loopCounter == 3)
            {
                System.out.println("This program will self destruct if you enter another invalid response.");
            }

        }//end of switch
    }//end of while
}//end of game start method

public static void walletDrop()
{
    System.out.println("wallet drop successful");
}

}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-10-15 06:29:31

所以我在发帖后就解决了这个问题。如果其他人需要在这里寻求帮助:

我遇到的问题是由于使用scanner方法造成的。

variableToAssign = scannerName.next();

而不是

variableToAssign = scannerName.nextLine();

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52807587

复制
相关文章

相似问题

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