如何让我的java程序包含大写和小写字符?

时间:2015-12-08 03:53:25

标签: java

我正在尝试在我的代码中包含可用字符的大写和小写字母,但我不知道如何解决这个问题。谁能给我一些见解?

以下是我目前为止的代码:

import java.util.Scanner;

public class ShopSign {

public static void main(String[] args) {
    // Scanner class//
    Scanner input = new Scanner(System.in);
    // variable to store available characters//
    String availableCharacters;     
    // variable to store proposed message//
    String proposedMessage;
    // variable to keep track if message will make it or not to the sign board//
    boolean flag = true;
    // variable to store the character that remain short//
    char shortCharacter = ' ';
    // variable to store character at current position//
    char temp;                      

    // Prompt for input of available characters//
    System.out.println("Enter available characters:");
    // read available characters
    availableCharacters = input.nextLine();

    // Prompt for input of proposed message//
    System.out.print("Enter proposed message: ");
    // read proposed message//
    proposedMessage = input.nextLine();


    // remove white spaces from the message//
    proposedMessage = proposedMessage.replaceAll("\\s","");

    //check if character it is available//
    for(int i = 0; i < proposedMessage.length(); i++){
        temp = proposedMessage.charAt(i);

        // if character is not the whitespace//
        if(temp != ' '){
            // check if character is available//
            if(availableCharacters.indexOf(temp) >= 0){
                // replace the character to empty string from available characters//
                availableCharacters = availableCharacters.replaceFirst(Character.toString(temp), "");
            }
            // otherwise mark the flag false and break the loop//
            else{
                flag = false;
                shortCharacter = temp;
                break;
            }
        }
    }

    // Print the appropriate message to the user//
    if(flag){
        System.out.println("The message makes it to the sign board.");
    }
    else{
        System.out.println("We are short of character "+ Character.toString(shortCharacter) +".");
        }
    input.close();
    }
}

2 个答案:

答案 0 :(得分:0)

你到底希望做什么?在使用您的代码并使用aAbB作为可用字母后,我输入AaBb作为我建议的消息,并输出“This message makes it to the sign board.

EDIT;如果您希望只允许任何一个字符(大写和小写),您可以这样做:

availableCharacters = availableCharacters.replaceFirst(Character.toString(temp).toLowerCase(), "");
availableCharacters = availableCharacters.replaceFirst(Character.toString(temp).toUpperCase(), "");

答案 1 :(得分:0)

您的期望不明确,但我对您的代码提出了建议:

  1. 不需要检查if(temp != ' '),因为您已经清空了空间 上一段代码的字符:

    proposedMessage = proposedMessage.replaceAll(“\ s”,“”);

  2. 如果proposedMessage包含special,则代码将失败 字符(例如:+ \ ...)

    在使用replaceFirst之前需要使用Pattern.quote:

    String pattern = Pattern.quote(Character.toString(temp));
    availableCharacters = availableCharacters .replaceFirst(pattern, "");