加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

条件短,java

发布时间:2020-12-15 01:59:49 所属栏目:Java 来源:网络整理
导读:我想测试当前的char当前是不是’,’,’ – ‘,’.’要么 ‘ ‘ 是否有更短的表达式: if((current != ' ') || (current != '.') || ...) 有任何想法吗? 编辑: 我只是被允许使用方法nextChar和getChar.我必须遍历字符. import java.io.FileInputStream;impo
我想测试当前的char当前是不是’,’,’ – ‘,’.’要么 ‘ ‘
是否有更短的表达式:

if((current != ' ') || (current != '.') || ...)

有任何想法吗?

编辑:

我只是被允许使用方法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;
    }
}

解决方法

如果你不允许使用String.indexOf,如:

if (" .,".indexOf(ch) != -1) {
        /* do something */
    } else {
        /* do if none of the above */
    }

使用像中的开关

switch (ch) {
        case ' ': case '.': case ',': /* do something */ break;
        default: /* do if none of the above */ break;
    }

(而不是保存以前的char,您可以使用布尔值来指示前一个char是单词边界还是合法单词字符)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读