简体   繁体   English

Java:如果用户输入不是单个字母小写字母,如何将用户返回主菜单?

[英]Java: How do I return user to main menu if user input is not a single alphabetic lowercase letter?

I'm trying to run a program that will allow the user to input both a char keyCharacter and a String theString. 我正在尝试运行一个允许用户同时输入char keyCharacter和String theString的程序。 Then, using these inputs, I will mask the keyCharacter if it occurs in theString with a "$", remove the keyCharacter from the theString, and finally, count the number of times the keyCharacter occurs in theString altogether. 然后,使用这些输入,我将屏蔽keyCharacter,如果它出现在带有“$”的字符串中,从theString中删除keyCharacter,最后计算keyCharacter在字符串中出现的次数。

Every method is working fine, except the method getKeyCharacter where the user has to input a char: The user can only enter a single letter (eg q, or z). 每个方法都正常工作,除了方法getKeyCharacter,用户必须输入一个char:用户只能输入一个字母(例如q或z)。

If the user enters anything other than that single letter (which can be anything from a word, phrase, sentence, special character like # or $, blank space or tabs, or just pressing enter), then the program returns the user to the original question that asks for the keyCharacter from the user. 如果用户输入除单个字母以外的任何内容(可以是单词,短语,句子,特殊字符,如#或$,空格或制表符,或只需按Enter键),则程序会将用户返回到原始字母从用户那里请求keyCharacter的问题。 This should continue looping back to that original question until the user enters a valid input. 这应该继续循环回到原始问题,直到用户输入有效输入。

Since I'm still a beginner to java and loops are my weakness so far, this part is causing me a lot of trouble. 由于我还是Java的初学者,循环是我目前的弱点,这部分给我带来了很多麻烦。 I know I should be using a while loop, it is the logic behind the nested loops that is really confusing me. 我知道我应该使用while循环,这是嵌套循环背后的逻辑真的令我感到困惑。

From searching for possible solutions, I know there are these things called regex and try-catch exception that could help with my issue, but since we haven't gone over that explicitly in class, I'd prefer not to deal with that for now. 从搜索可能的解决方案,我知道有一些叫做正则表达式和try-catch异常的东西可以帮助解决我的问题,但是由于我们没有在课堂上明确地解决这个问题,所以我现在不想处理这个问题。 。 Thank you. 谢谢。

Here's a paste of my code: 这是我的代码粘贴:

import java.util.*;

public class Foothill {

    // main method
    public static void main (String[] args) {
        char keyCharacter = getKeyCharacter();
        String theString = getString();    
        maskCharacter(theString, keyCharacter);
        countKey(theString, keyCharacter);
        removeCharacter(theString, keyCharacter);
    }

    // get keyCharacter
    public static char getKeyCharacter() {
        Scanner inputStream = new Scanner(System.in);
        boolean stop = false;
        String firstPrompt, strKeyCharacter;
        char keyCharacter = ' ';

        while (stop != true) {
            firstPrompt = "Please enter a SINGLE character to act as key: ";
            System.out.print(firstPrompt);
            strKeyCharacter = inputStream.nextLine(); 

            while (strKeyCharacter.length() != 1) {
                firstPrompt = "Please enter a SINGLE character to act as key: ";
                System.out.print(firstPrompt);
                strKeyCharacter = inputStream.nextLine();
            }

            keyCharacter = strKeyCharacter.charAt(0);

            while (strKeyCharacter.length() == 1) {
                firstPrompt = "Please enter a SINGLE character to act as key: ";
                System.out.print(firstPrompt);
                strKeyCharacter = inputStream.nextLine();
                if (keyCharacter == 'a' || keyCharacter == 'b' || keyCharacter == 'c' || keyCharacter == 'd' 
                  || keyCharacter == 'e' || keyCharacter == 'f' || keyCharacter == 'g' || keyCharacter == 'h'
                  || keyCharacter == 'i' || keyCharacter == 'j' || keyCharacter == 'k' || keyCharacter == 'l'
                  || keyCharacter == 'm' || keyCharacter == 'n' || keyCharacter == 'o' || keyCharacter == 'p'
                  || keyCharacter == 'q' || keyCharacter == 'r' || keyCharacter == 's' || keyCharacter == 't'
                  || keyCharacter == 'u' || keyCharacter == 'v' || keyCharacter == 'w' || keyCharacter == 'x'
                  || keyCharacter == 'y' || keyCharacter == 'z') {
                    System.out.println("You entered: " + keyCharacter + '\n');
                    stop = true;
                } else {
                    break;
                }
            }
        }
        return keyCharacter;
    }

    // declare final = 4 to be constant
    public static final int minimumLength = 4;

    // get theString
    public static String getString() {
        Scanner inputStream = new Scanner(System.in);
        String secondPrompt, theString;
        do {
            secondPrompt = "Please enter a phrase or sentence >= 4: ";
            System.out.print(secondPrompt);
            theString = inputStream.nextLine();
            System.out.print('\n');
        } while (theString.length() < minimumLength || theString == null || theString.length() == 0);
        inputStream.close();
        return theString;
    }

    // mask keyCharacter with $
    public static String maskCharacter(String theString, char keyCharacter) {
        theString = theString.replace(keyCharacter, '$');
        System.out.println("String with " + " '" + keyCharacter + "' " + " masked.");
        System.out.println(theString + '\n');
        return theString;
    }

    // count number of times keyCharacter occurs in theString
    public static void countKey(String theString, char keyCharacter) {
        int countChar = 0;
        for (int charTimes = 0; charTimes < theString.length(); charTimes++) {
            if (theString.charAt(charTimes) == keyCharacter) {
                countChar++;
            }
        }
        System.out.println( "The key character occurs " + countChar + " times. \n");
        return;
    }

    // remove keyCharacter from theString
    public static void removeCharacter(String theString, char keyCharacter) {
        theString = theString.replace(String.valueOf(keyCharacter), "");
        System.out.println("String with " + "'" + keyCharacter + "' removed: ");
        System.out.println(theString);
        return;
    }
}

And here's a paste of my run (as you can see, there is some serious debugging to be done in my program): 这是我的运行粘贴(你可以看到,在我的程序中有一些严肃的调试):

Please enter a SINGLE character to act as key: f
Please enter a SINGLE character to act as key: f
You entered: f

Please enter a SINGLE character to act as key: f
You entered: f

Please enter a SINGLE character to act as key: f
You entered: f

Please enter a SINGLE character to act as key: f
You entered: f

Please enter a SINGLE character to act as key: 

// which then continues so on so forth...
public static char getKeyCharacter(){

    Scanner inputStream = new Scanner(System.in);
    boolean stop = false;
    String firstPrompt, strKeyCharacter;
    char keyCharacter = ' ';

    while(!stop){

        firstPrompt = "Please enter a SINGLE character to act as key: ";
        System.out.println(firstPrompt);
        strKeyCharacter = inputStream.nextLine();

        //check if the input contains only 1 character
        boolean isSingleChar = (strKeyCharacter.length() == 1);
        //check if the input character is within the ASCII code of 97 (a) to 122 (z)
        boolean isValidChar = 
                strKeyCharacter.charAt(0) >= 97 &&
                strKeyCharacter.charAt(0) <= 122;

        if(isSingleChar && isValidChar){
            keyCharacter = strKeyCharacter.charAt(0);
            stop = true;
        }


    }

    return keyCharacter;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何打印用户在Java中输入的字符串的一个字母? - How do I print one letter of a string that was input by the user in Java? 如何在没有用户输入的情况下自动返回主菜单? - How to automatically return to main menu without user input? 使用 switch 语句时如何将用户返回到主菜单? Java - How to return user to main menu when using switch statement? Java 用户输入upperCase和LowerCase-Java - User input upperCase and lowerCase - Java 如何验证用户是否在Java中输入整数或字母字符? - How can I verify that a user enters an integer or alphabetic character in Java? 如何验证 Java 中的用户输入 - How do I validate user input in Java 如何将多行 txt 添加到数组中并将每个字母与用户输入的字母进行比较? - How do I add multiple lines of txt into an array and compare each letter to a user-input letter? 如何检查 Java 字符串是否至少包含一个大写字母、小写字母和数字? - How do I check if a Java String contains at least one capital letter, lowercase letter, and number? 如何将用户输入(字符串)返回到只有第一个字母大写的地方 - How to return user input (string) to where only the first letter is capitalized 在Java中完成条件的一条路径后,如何返回用户输入? - How do I return to user input after completing one path of a conditional in java?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM