本文介绍了如果输入不等于切换中的大小写,如何让用户重新输入数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近学习了 Java,我有一个 switch 语句可以从另一个类中获取用户输入 ,我想知道如何使 defaultcase for my switch 语句使用户重新输入数据.

I recently learned Java and I have a switch statement that gets user input from another class and i was wondering how to make the default case for my switch statement make the user re-input data.

目前我有以下基本代码

static int getMonthInt(String monthName)
{
    switch(monthName.trim())
    {
        case "January":
            return 1;
        case "Febuary":
            return 2;
        case "March":
            return 3;
        case "April":
            return 4;
        case "May":
            return 5;
        case "June":
            return 6;
        case "July":
            return 7;
        case "August":
            return 8;
        case "September":
            return 9;
        case "October":
            return 10;
        case "November":
            return 11;
        case "December":
            return 12;
        default:
            // what do i put here
    }

}

我从另一个类调用的输入类中获取用户输入,如下所示:

I get user input from an input class called from another class like so:

public static void main(String[] args) {

    String monthName;
    int dayNumber;
    int yearNumber;

    monthName = Input.getString("Please enter the current month name with a capital letter!");
    dayNumber = Input.getInt("Please enter the current day!");
    yearNumber = Input.getInt("Please enter the current year!"); }

这一切都有效.然而,我的问题是,如果有人输入了无效的输入,例如ovtomber",我希望用户被重新提示输入数据.我会把它放在 switch 的默认情况下还是放在main 方法(我在那里获得用户输入)还有我将如何做到这一点(我尝试了两种方法但无法获得预期的行为,并且我找不到有关输入验证的任何主题)?

This all works. My problem is however that if someone enters an invalid input such as 'ovtomber' I want the user to be re-prompted to enter data. Would I put this in the default case of the switch or in the main method (where I get user input) also how would i do this (I tried both ways and couldnt get the expected behavior & I could not find any topics on input validation)?

推荐答案

在你的 switch 语句中,你默认返回一个明显无效的月份(通常是 -1):

In your switch statement you have the default return an obviously invalid month (commonly -1):

default:
    return -1;

然后在你的逻辑中,如果结果是-1,你可以要求澄清,例如:

Then in your logic, you can request clarification if the result is -1, eg:

int validatedMonth;
do
{
    monthName = Input.getString("Please enter the current month name with a capital letter!");
    validatedMonth = getMonthInt(monthName);
    if(validatedMonth == -1)
        System.out.println("Invalid month name, please try again");
} while (validatedMonth == -1);

(示例代码,我没有检查它是否编译)

(example code, I haven't checked it compiles)

这篇关于如果输入不等于切换中的大小写,如何让用户重新输入数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 20:29
查看更多