【问题标题】:Checking a string for invalid characters检查字符串中的无效字符
【发布时间】:2018-01-24 21:35:35
【问题描述】:

我正在尝试编写一个将字符串作为输入的程序。

这个字符串必须是一个只有括号、运算或数字的方程。

我在下面发布的代码是我想出的,但是当我运行它时,我输入的任何内容显然都是无效的字符串。谁能告诉我我做错了什么?

        System.out.println("Enter a string");                               
        String str = s.nextLine();   //s is a Scanner object                    
        int n = str.length();                                           

        for(int i = 0; i < n; i++) {                                        
            if( !Character.isDigit(str.charAt(i)) || str.charAt(i) != '+'
                || str.charAt(i) != '-' || str.charAt(i) != '*'
                || str.charAt(i) != '/' || str.charAt(i) != '('
                || str.charAt(i) != ')' || str.charAt(i) != '['
                || str.charAt(i) != ']' || str.charAt(i) != '{'
                || str.charAt(i) != '}') {
                    System.out.println("invalid string, try again: ");
                    str = s.nextLine();     
            }
        ...}

【问题讨论】:

  • 每个字符都不是'-'或不是'+'。我想你想要 && 不是 || .
  • 如果你讨厌自己,那当然。我宁愿保持清晰。
  • 此外,通常在方程式中允许空格(“1 + 2”而不是“1+2”),而您的规范不允许这样做。另外,带有不平衡括号 ("1)+2") 的方程仍然可以通过您的测试。我认为直接进行解析而不用担心“字符”可能会更好。
  • @svasa 我不同意。当包含或实际解析可以时,这是一个可怕的正则表达式(特别是在 Java 中)。可维护性和易读性几乎总是胜过其他任何事情。
  • @Jason Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems. blog.codinghorror.com/…

标签: java string char


【解决方案1】:

按照 cmets 中的建议,将 || 切换为 &amp;&amp;

if( !Character.isDigit(str.charAt(i)) && str.charAt(i) != '+'
        && str.charAt(i) != '-' && str.charAt(i) != '*'
        && str.charAt(i) != '/' && str.charAt(i) != '('
        && str.charAt(i) != ')' && str.charAt(i) != '['
        && str.charAt(i) != ']' && str.charAt(i) != '{'
        && str.charAt(i) != '}') {
    System.out.println("invalid string, try again: ");
    str = s.nextLine();     
}

或者,为了让您的代码更易于理解:

final String validChars = "0123456789+-*/()[]{}";
for(int i = 0; i < n; i++) {
    if(!validChars.contains(str.charAt(i))) {
        System.out.println("invalid string, try again: ");
        str = s.nextLine();
        // potential bug here - i and n are not being reset
    }
}

注意:如果您的前一行包含一个无效字符(参见上面代码中的注释)。

【讨论】:

  • 简单地说..!这应该被标记为正确答案。
  • @Franklin 如果此答案解决了您的问题,请考虑通过单击左侧的绿色复选标记来接受它。
【解决方案2】:

如果您不想更改所有代码,您可以这样做:

 System.out.println("Enter a string");

    String str = s.nextLine(); // s is a Scanner object
    int n = str.length();

    if (n > 0) {
        for (int i = 0; i < n; i++) {
            if (!(Character.isDigit(str.charAt(i)) || str.charAt(i) == '+' || str.charAt(i) == '-'
                    || str.charAt(i) == '*' || str.charAt(i) == '/' || str.charAt(i) == '(' || str.charAt(i) == ')'
                    || str.charAt(i) == '[' || str.charAt(i) == ']' || str.charAt(i) == '{'
                    || str.charAt(i) == '}')) {
                System.out.println("invalid string, try again: ");
                str = s.nextLine();
                n = str.length();
                i = -1;//reset i for the new line ( set at -1 for the next i++ of the next loop )
            }
        }
    } else {
        System.out.println("empty string ");
    }

【讨论】:

  • 这改变了所有的代码,只是以不同的方式:/
【解决方案3】:
package hello;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

import org.junit.Test;

public class Characts {

    @Test
    public void testSwitch () {
         assertTrue(isValid("123+321*"));
         assertFalse(isValid("A123+321*"));
         assertTrue(isValid("123+321*\n")); // don't forget returns and line feeds
    }

    private boolean isValid(String str) {
        for (int i = 0 ; i < str.length(); i++) {
            char s = str.charAt(i);
            if (Character.isDigit(s)) {
                continue;
            } else {
                switch (s) {
                case '+' :
                case '-' :
                case '*' :
                case '/' :
                case '(' :
                case ')' :
                case '[' :
                case ']' :
                case '{' :
                case '}' :
                    continue;
                }
                return false;
            }
        }
        return true;
    }
}

【讨论】:

    猜你喜欢
    • 2021-07-20
    • 1970-01-01
    • 2021-09-02
    • 1970-01-01
    • 2013-02-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多