Java - 只识别字符串中的字母

时间:2017-11-19 22:39:58

标签: java string ignore letters

我想实现一个程序,用户可以在其中输入任何字符串,它只显示在控制台上的字母。如果输入字母以外的字符串,则应通知用户。到目前为止,我已经获得了一些代码,但是当我进入例如#34;我爱你#34;,"那么多。"输出应该是" ILoveYou这么多",但它确实不会像这样工作,因为现在的输出是"我爱你这么多"。我的代码中的错误在哪里?

// Input
int i = 0;
write("Please enter consecutively at least one word (only letters) and finish it with an empty one.");
String input = readString("Enter a word:");
while(input.length() == 0) { // Enter at least one word
    input = readString("Wrong input. Enter at least one word:");
}
while(input.length() != 0) { // End input by an empty String
    while(i < input.length()) { // Iterate through input
        char text = input.charAt(i);
        if(text >= 'a' && text <= 'z') { // Check lower case letters
            if(text >= 'A' && text >= 'Z') { // Check upper case letters
                if(text == 'ä' || text == 'ö' || text == 'ü' || text == 'ß'){ // Check mutated vowel
                    text = input.charAt(i-1); // Ignore wrong input
                    write("Wrong input.");
                }   
            }
        } 
    ++i;
}
String inPut = input +" ";
System.out.print(inPut);
input = readString("Enter a word:");    

}

4 个答案:

答案 0 :(得分:1)

您可以使用以下代码,希望它会有所帮助。

 int i = 0;
    System.out.println("Please enter consecutively at least one word (only letters) and finish it with an empty one.");
    Scanner lire=new Scanner(System.in);
    String input = lire.nextLine();
    while(input.length() == 0) { // Enter at least one word
        System.out.println("Wrong input. Enter at least one word:");
        input = lire.nextLine();
    } 

    String output="";
    while(input.length() != 0){ 
        while(i < input.length()) { 
            char text = input.charAt(i);
            if( (text >= 'a' && text <= 'z') || ( text >= 'A' && text <= 'Z') || text == 'ä' || text == 'ö' || text == 'ü' || text == 'ß' || text==' ' ) { 
               output=output+text;
            } 

            ++i;
        } 
        System.out.println("Input : "+input);
        System.out.println("Output : "+output);
        System.out.println("Enter a word:");
        input = lire.nextLine();
    }

输出:

Please enter consecutively at least one word (only letters) and finish it with an empty one.
I-Love-you so much.
Input : I-Love-you so much.
Output : ILoveyou so much
Enter a word:

答案 1 :(得分:1)

现在看起来,你正在设置readString的输入,但是循环实际上并没有做任何事情。文本已设置但从未使用过。退出while循环后,初始值会添加一个空格并打印出来,无需修改,这就是原始字符串出来的原因。

至于改进这一点,将第一个更改为if语句,就像它尝试做的那样。使用for循环迭代字符串 - 更好的是,对每个循环使用增强的/:

for(char c : input) {
    // stuff here
}

看起来你也会调用相同的方法来结束一堆疯狂的调用 - 相反,如果输入有问题你真的想从函数的开头再次开始。希望这会给你一个开始

编辑:示例

while(true) {
    System.out.println("Please enter consecutively at least one word (only letters) and finish it with an empty one.");
    Scanner sc = new Scanner(System.in);
    String input = sc.nextLine();    
    StringBuilder result = new StringBuilder();
    if (input.length() == 0) {
        System.out.println("Please enter at least one word");
    }
    if (input.length() > 0) {
        for (char c : input) {
            // validate your characters
            result.append(c);
        }
        System.out.println(result.toString());
        // optionally use return here to end the loop
    }
}  

你当然可以使用字符串连接,但StringBuilder也很好。您只需将字符转换为字符串(Character.toString(c))即可。 请注意,我们处于while(true)的无限循环中,如果我们没有单词,循环将从头开始,因为我们不会执行第二个if语句。

答案 2 :(得分:1)

您可能希望查看正则表达式。例如,.matches("[a-zA-Z]")仅匹配字母。

String str = "I-Love-You so 234much'^Br7u..h.";
StringBuilder sb = new StringBuilder();
char[] arrr = str.toCharArray();
for (char c : arrr) {
    // I'm sure there's a way to include the space in the regex but I don't know how to
    if (String.valueOf(c).matches("[a-zA-Z]") || String.valueOf(c).matches(" ")) {
        sb.append(c);
    }
}
System.out.println(sb.toString());

输出:ILoveYou so muchBruh

答案 3 :(得分:1)

我无法使用readString方法,所以我使用了正则表达式。希望这会有所帮助。

import java.util.regex.*;
import java.util.Scanner;

public class wordSieve 
{

    public static void main(String[] args)
    {
        String str;
        StringBuilder c = new StringBuilder();
        Scanner input = new Scanner(System.in);
        System.out.println("Please enter consecutively at least one word (only letters) and finish it with an empty one.");
        str = input.nextLine();

        while (str.length() != 0)
        {   
            // Find a to z or A to Z at least of length 1
            // maybe starting and ending with whitespace.
            regexChecker("\\s?[A-Za-z]\\s?{1,}", str, c);
            System.out.print("");
            str = input.nextLine();
        }
        System.out.print(c);
    }

    public static void regexChecker(String theRegex, String str2Check, StringBuilder outputStr) {
        Pattern checkRegex = Pattern.compile(theRegex);
        Matcher regexMatcher = checkRegex.matcher(str2Check);
        while (regexMatcher.find()) // find all the matches
        {
            if (regexMatcher.group().length() != 0)
            {
                outputStr.append(regexMatcher.group());
            }
        }
    }
}