0

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.

Why isn't the nested loop adding value separately, instead of adding all together?

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]);
        }
    }   
}
1
  • As comments on your coding style that will help you in the future, I would add print statements (similar to the one commented out) to identify what values need to be entered each time sc.next() is used.Also I would add print statements at selected points in the code to display important values at key statements. (these should be removed before the code is turned in for grading). Commented Oct 8, 2015 at 23:46

1 Answer 1

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

    ...
}

You need to reset totalHole to 0 each time you start the outer loop. The best way to do that is to move its declaration inside the loop.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.