条件短,java

Upv*_*ote 3 java optimization expression

我想测试当前的char 当前是不是',',' - ','.' 或'' 是否有更短的表达:

if((current != ' ') || (current != '.') || ...)
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

编辑:

我只是被允许使用方法nextChar和getChar.我必须遍历字符.

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

public class WoerterZaehlen {
    public static void main(String[] args) {
        int wordCount = 0;
        /* Ab hier dürft ihr eigenen Code einfügen */
        char previous = ' ';
        while(hasNextChar()){
            char current = getChar();
            if(current != )
            //if(((current == ' ') || (current == '.') || (current == ',')) && ((previous != ' ') && (previous != ','))){
            //  wordCount++;
            //}
            previous = current;         
        }
        /* Ab hier dürft ihr nichts mehr ändern. */
        System.out.println("Anzahl der Wörter: " + wordCount);
    }

    private static InputStreamReader reader;
    private static int next = -1;

    public static boolean hasNextChar() {
        if(next != -1)
            return true;
        try {
            if(reader == null)
                reader = new InputStreamReader(new FileInputStream("textdatei.txt"));
            next = reader.read();

        } catch (IOException e) {
            System.out.println("Datei wurde nicht gefunden.");
        }
        return next != -1;
    }

    public static char getChar() {
        char c = (char) next;
        next = -1;
        return c;
    }
}
Run Code Online (Sandbox Code Playgroud)

Syn*_*sso 13

尝试

String prohibitedChars = ",-. ";
boolean isProhibited = prohibitedChars.indexOf('-') > -1;
Run Code Online (Sandbox Code Playgroud)

我清理它看起来有点不错,但如果你真的很简单,那么你所需要的只是:

",-. ".indexOf('-') > -1;
Run Code Online (Sandbox Code Playgroud)

编辑:

即使你只限于getChar()和hasNextChar(),你仍然可以使用这种方法

while(hasNextChar()){
    char current = getChar();
    if (",-. ".indexOf(current) > -1) {
        wordCount++;
    }
    previous = current;         
}
Run Code Online (Sandbox Code Playgroud)