简体   繁体   中英

Issue with resetting data with a do while loop (Java)

I'm working on a program for school where I need to sort how many vowels are in a string along with the # of non-vowels. My teacher wants us to ask the user if they want to continue so we can provide multiple test cases without running the program more than once. I successfully got the program to loop, but my problem is that the vowel and non-vowel numbers from the previous test case carry over to the next one. I've been searching around online for the solution but I've had no luck so far. Any help would be much appreciated. (I am a noob at programming btw, I still have much to learn.)

 import java.util.*; class VowelReader { public static void main(String[] args) { String line; int vi= 0, a = 0, e = 0, o = 0, u = 0, nonvowels = 0; String answer = null; Scanner scan = new Scanner (System.in); do { System.out.println("Enter a String to be processed for vowels: "); line = scan.nextLine( ); for(int i = 0; i < line.length(); i++){ char c = Character.toLowerCase(line.charAt(i)); switch (c) { case 'a': a++; break; case 'e': e++; break; case 'i': vi++; break; case 'o': o++; break; case 'u': u++; default: nonvowels++; break; } } System.out.println(line); System.out.println("a- " +a); System.out.println("e- " +e); System.out.println("i- " +vi); System.out.println("o- " +o); System.out.println("u- " +u); System.out.println("Non-vowels -" +nonvowels); System.out.println("Continue?(Y/N)"); answer = scan.nextLine(); } while( answer.toLowerCase().equals( "y" ) ); } } 

Using a Map with the key as a String you can keep track of our counts in one object. You then could put as many Maps, one for each test/string into a List . Then you can loop over the list preforming the same test(s) on different data sets.

Being homework and all I'm not going to post any code.

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