gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 04:18:46 25 4
gpt4 key购买 nike

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/

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