java - 为什么嵌套循环不单独添加值,而是将所有值加在一起?

标签 java nested-loops

Chef wrote some text on a piece of paper and now he wants to know how many holes are in the text. What is a hole? If you think of the paper as the plane and a letter as a curve on the plane, then each letter divides the plane into regions. For example letters "A", "D", "O", "P", "R" divide the plane into two regions so we say these letters each have one hole. Similarly, letter "B" has two holes and letters such as "C", "E", "F", "K" have no holes. We say that the number of holes in the text is equal to the total number of holes in the letters of the text. Help Chef to determine how many holes are in the text.

为什么嵌套循环不单独添加值,而是将所有值加在一起?

public class Practice{
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        int totalnumber = sc.nextInt();
        String[] noString = new String[totalnumber];

        for(int i = 0; i < totalnumber; i++){
            //System.out.println("Enter the word for " + i);
            noString[i] = sc.next();
        }

        int totalHole = 0;
        int[] total = new int[totalnumber];

        char[] singleHole = {'A','Q','R','O','P','D'};
        char B = 'B';
        int counter = 0;

        for(int a = 0; a < totalnumber; a++){
            for(int i = 0; i < noString[counter].length();i++){
                for(int j = 0; j < singleHole.length; j++){
                    if(noString[a].charAt(i) == singleHole[j]){
                        totalHole = totalHole + 1;
                    }
                }
                if(noString[a].charAt(i) == B){
                    totalHole = totalHole + 2;
                }
            }
            counter = counter + 1;
            total[a] = totalHole;
            System.out.println(total[a]);
        }
    }   
}

最佳答案

for(int a = 0; a < totalnumber; a++){
    int totalHole = 0;

    ...
}

每次启动外循环时,您都需要将totalHole重置为0。最好的方法是将其声明移到循环内。

关于java - 为什么嵌套循环不单独添加值,而是将所有值加在一起?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33027362/

相关文章:

java - 如何在不留下空字符串的情况下拆分字符串?

在测试用例/不同类中调用构造函数时,Java 类值被覆盖

php - 在嵌套循环中使用数组耗尽内存

PHP 分层数组 - 检查子值是否存在,然后将父属性值分配给其子数组

ruby - 如何打破 Ruby 中的嵌套循环?

scheme - Racket /方案中的惯用嵌套循环

java - 有什么方法可以找出最后一次在 Java 中访问字符串/整数是什么时候?

java - 如何使用 map.key 包含字符串值?

java - hazelcast 分布式加载是阻塞的吗?

android - 如何防止我的程序排队按钮按下