简体   繁体   中英

Resetting Counter Java

import java.util.Scanner;
public class VowelsAndConsonants {
public static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
    int ConsonantCount = 0;
    int VowelCount = 0;
    int num = 0;
    int x = 0;
    while(true) {
        System.out.print("Enter a string: ");
        String userInput = input.next();
        num = userInput.length();
        for(x = 0; x < num ; x++) {
            char c = userInput.charAt(x);
            if (Character.isLetter(c)){
                c = Character.toUpperCase(c);
                if (c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U') 
                    VowelCount++;
                else 
                    ConsonantCount++;


            }


        }
        System.out.println("The number of vowels is: " + VowelCount);
        System.out.println("The number of consonants is: " + ConsonantCount);




        System.out.println("Do you want to enter another string? ");
        String loopAgain = input.next();
        if (loopAgain.equalsIgnoreCase("N")) {
            break;
        }

    }
}

}

How do I reset the VowelCount and ConsonantCount after looping again? Currently, it's adding onto the counter without resetting to zero. Please help. My instructor wants me to break out of the loop if I say N or loop again if its any other character

I'm assuming you want to reset it after you print? All you need to do is assign it like any other variable

System.out.println("The number of vowels is: " + VowelCount);
System.out.println("The number of consonants is: " + ConsonantCount);
ConsonantCount = 0;
VowelCount = 0;

Another route you could take would be to declare your variables at the beginning of the while loop. This way, every time the while loop runs, it re-initializes the variables to zero, so you don't have to even reset it.

while (true) {
    int ConsonantCount = 0;
    int VowelCount = 0;
    ....
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM