Java – 用枚举类型捕捉用户输入的错误

huangapple go评论67阅读模式
英文:

Java - Error catching user-input with enums

问题

我在Java中定义了一个enum,用于验证用户输入。我遇到了一个问题,如果用户输入了一些内容,程序就会退出,而不会像我预期的那样循环。

我希望能够循环,直到用户输入了列表中的一项。

以下是相关的代码:

// import System.out
import static java.lang.System.out;

// import scanner for user-input
import java.util.Scanner;

public class AnimalTest {

    // enum for user-input
    enum animal {

        COW,
        DUCK,
        PIG,
        SHEEP

    }

    public static void main(String[] args) {

        // create scanner for user input
        Scanner userInput = new Scanner(System.in);
        animal selection = null; // 初始化选择变量

        do {
            // print out menu
            out.println("Which animal are you?\nCow\nDuck\nPig\nSheep");

            // get user-input and validate against enum
            try {

                selection = animal.valueOf(userInput.nextLine().toUpperCase());

            } catch (Exception e) {

                out.println("Please type in one of the animals above.");

            } finally {
                break;
            }
        }
        while (true);

        // switch based on validated user input
        switch (selection) {

            case COW:

                cow cow0 = new cow();
                cow0.sound();
                break;

            case DUCK:

                duck duck0 = new duck();
                duck0.sound();
                break;

            case PIG:

                pig pig0 = new pig();
                pig0.sound();
                break;

            case SHEEP:

                sheep sheep0 = new sheep();
                sheep0.sound();
                break;

        } // end switch

    } // end main

} // end class

在这之后,我将使用switch语句。编译器报告的一个错误是变量selection未定义,因此无法在switch语句中使用它。希望这方面的解释也能对您有所帮助。

英文:

I have defined an enum in java to use that for validating user input. I am having an issue where if the user puts in something the program just exits and doesn't loop that way I'm expecting it to.

I want to be able to loop until the user has inputted one of the items on the list.

Here's the code in question:

// import System.out
import static java.lang.System.out;
// import scanner for user-input
import java.util.Scanner;
public class AnimalTest {
// enum for user-input
enum animal{
COW,
DUCK,
PIG,
SHEEP
}
public static void main(String[] args){
// create scanner for user input
Scanner userInput = new Scanner(System.in);
do {
// print out menu
out.println("Which animal are you?\nCow\nDuck\nPig\nSheep");
// get user-input and validate against enum
try{
animal selection = animal.valueOf(userInput.nextLine().toUpperCase());
}
catch (Exception e){
out.println("Please type in one of the animals above.");
}
finally{
break;
}
}
while (true);
// switch based on validated user input
switch(selection){
case COW:
cow cow0 = new cow();
cow0.sound();
break;
case DUCK:
duck duck0 = new duck();
duck0.sound();
break;
case PIG:
pig pig0 = new pig();
pig0.sound();
break;
case SHEEP:
sheep sheep0 = new sheep();
sheep0.sound();
break;
}// end switch
}// end main
}// end class

After this, I am going to use a switch and one of the errors the compiler is throwing at me is that the variable selection is not defined so I can use the switch on it, any insight on this aspect as well is apprciated

答案1

得分: 2

我认为你的问题在于你的“动物选择”变量在try块中被定义为局部变量,因此当你到达switch case时,它已经超出了作用域。

我有这段代码(我进行了一些小的更改以使其能够运行),它可以正常工作。我首先声明并初始化了变量(即使将其初始化为null也可以)。

import static java.lang.System.out;

// 导入用于用户输入的Scanner
import java.util.Scanner;

public class AnimalTest {

    // 用于用户输入的枚举
    enum Animal {

        COW,
        DUCK,
        PIG,
        SHEEP

    }

    public static void main(String[] args) {

        // 创建用于用户输入的Scanner
        Scanner userInput = new Scanner(System.in);
        Animal selection = null;
        do {
            // 打印菜单
            out.println("你是哪种动物?\n牛\n鸭\n猪\n羊");

            // 获取用户输入并根据枚举进行验证
            try {

                selection = Animal.valueOf(userInput.nextLine().toUpperCase());

            } catch (Exception e) {

                out.println("请在上述动物中选择一个进行输入。");

            } finally {
                break;
            }
        } while (true);

        // 根据经过验证的用户输入进行切换
        switch (selection) {

            case COW:

                out.println("牛");
                break;

            case DUCK:

                out.println("鸭");
                break;

            case PIG:

                out.println("猪");
                break;

            case SHEEP:

                out.println("羊");
                break;
            default:
                out.println("不是预期的动物");

        }// 结束switch

    }// 结束main

}// 结束class
英文:

I believe your issue is that your "animal selection" variable is defined locally in the try block, thus it is out of scope by the time you get to the switch case.

I have this code (with minor changes for things to run for me) and it works. I declared and initialized (even initialization to null is fine) first.

import static java.lang.System.out;
//import scanner for user-input
import java.util.Scanner;
public class AnimalTest {
// enum for user-input
enum Animal{
COW,
DUCK,
PIG,
SHEEP
}
public static void main(String[] args){
// create scanner for user input
Scanner userInput = new Scanner(System.in);
Animal selection = null;
do {
// print out menu
out.println("Which animal are you?\nCow\nDuck\nPig\nSheep");
// get user-input and validate against enum
try{
selection = Animal.valueOf(userInput.nextLine().toUpperCase());
}
catch (Exception e){
out.println("Please type in one of the animals above.");
}
finally{
break;
}
}
while (true);
// switch based on validated user input
switch(selection){
case COW:
out.println("cow");
break;
case DUCK:
out.println("duck");
break;
case PIG:
out.println("pig");
break;
case SHEEP:
out.println("sheep");
break;
default: out.println("not the expected animal");
}// end switch
}// end main
}// end class

答案2

得分: 2

除了@mauvecrow的回答中指出的问题之外,你的do/while循环是无用的。finally块总是会执行,所以你的while循环最终总是会在最后中断。你可以将break语句删除,并删除整个'while'结构。也许你的意图是要循环,直到输入了正确的答案?那么就将break语句放在selection =这行的后面,在try块内部。

英文:

Aside from the problem highlighted by @mauvecrow's answer, your do/while is useless. a finally block ALWAYS runs, so your while loop will always break at the end. You might as well delete the break, and the entire 'while' construct. Perhaps you intended to loop until a correct answer is entered? Then put the break after the selection = line, within the try block.

huangapple
  • 本文由 发表于 2020年9月30日 05:39:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/64128012.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定