我如何在Java中使用同一循环来限定三个不同的条件?

问题描述 投票:0回答:1

我想使用相同的循环而不是创建三个不同的循环来计算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);
            }
        }
    }
java
1个回答
0
投票

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

在您的for循环中编写以下内容:

Countsign += (element.match(sign)) ? 1 : 0;
CountX += (element.match(absenceX)) ? 1 : 0;
CountI += (element.match(absenceI)) ? 1 : 0;
© www.soinside.com 2019 - 2024. All rights reserved.