gpt4 book ai didi

java - 如何在 Java 中使用同一循环来确定三个不同条件的范围?

转载 作者:行者123 更新时间:2023-12-02 08:42:22 24 4
gpt4 key购买 nike

我想使用同一循环对 countXcountX 进行计数,而不是创建三个不同的循环。有什么简单的方法可以解决这个问题吗?

public class Absence {
private static File file = new File("/Users/naplo.txt");
private static File file_out = new File("/Users/naplo_out.txt");
private static BufferedReader br = null;
private static BufferedWriter bw = null;

public static void main(String[] args) throws IOException {
int countSign = 0;
int countX = 0;
int countI = 0;
String sign = "#";
String absenceX = "X";
String absenceI = "I";

try {
br = new BufferedReader(new FileReader(file));
bw = new BufferedWriter(new FileWriter(file_out));

String st;
while ((st = br.readLine()) != null) {
for (String element : st.split(" ")) {

if (element.matches(sign)) {
countSign++;
continue;
}
if (element.matches(absenceX)) {
countX++;
continue;
}
if (element.matches(absenceI)) {
countI++;
}
}
}
System.out.println("2. exerc.: There are " + countSign + " rows int the file with that sign.");
System.out.println("3. exerc.: There are " + countX + " with sick note, and " + countI + " without sick note!");
} catch (FileNotFoundException ex) {
Logger.getLogger(Absence.class.getName()).log(Level.SEVERE, null, ex);
}
}
}

文本文件示例:

# 03 26
Jujuba Ibolya IXXXXXX
Maracuja Kolos XXXXXXX

最佳答案

我认为您的意思是使用少于 3 个 if 语句。实际上你可以这样,没有 ifs。

在 for 循环中写下:

Countsign += (element.matches(sign)) ? 1 : 0;
CountX += (element.matches(absenceX)) ? 1 : 0;
CountI += (element.matches(absenceI)) ? 1 : 0;

关于java - 如何在 Java 中使用同一循环来确定三个不同条件的范围?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61302989/

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