gpt4 book ai didi

java - 短条件,java

转载 作者:搜寻专家 更新时间:2023-11-01 03:59:41 28 4
gpt4 key购买 nike

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

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 prohibitedChars = ",-. ";
boolean isProhibited = prohibitedChars.indexOf('-') > -1;

我把它清理干净了,让它看起来有点漂亮,但如果你真的想要short,那么你只需要:

",-. ".indexOf('-') > -1;

编辑:

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

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

关于java - 短条件,java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4040024/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com