简体   繁体   中英

Java- For loop with a switch statement containing default case. How can I get the default case to print the output only once?

The following default statement does exactly what its supposed to: catching all characters not mentioned in the above cases, AND notifying me (after running through the string), that there was an invalid character entered somewhere in there. However, if there was two invalid characters: the println statement will print twice. If there were three: three times, etc. In a string of 100,000 characters, it would be inefficient to print the line so many times.

How would I be able to get it to print only once, no matter how many invalid characters were entered? Please advise and thank you in advance for helping a Java novice!

  //for loop to calculate how many A's, G's, T's, and C's in the string
  //default statement at the end of the switch statements to weed out 
  //invalid characters. 
  for(int i=0; i < length; i++)
  {
     ch = dna.charAt(i);
     switch (ch)    
     {
        case 'A':   aCount++;
                    break;
        case 'C':   cCount++;
                    break;
        case 'G':   gCount++;
                    break;
        case 'T':   tCount++;
                    break;
        default: 
           System.out.println("An invalid character was entered.");
     }
  }
 import java.util.Scanner;
 //done by Nadim Baraky
 //this program calculates the number of A's, C's, G's & T's;
 //it prints a statement once as you wished in case invalid characters where entered

public class ACGT_DNA {


  public static void main (String[] args) {
     //the counter is set to be 1;
     int length, counter=1; 
     int aCount =0, cCount=0, gCount =0, tCount=0;

     char ch;

     Scanner scan = new Scanner(System.in);
     System.out.print("Enter your string: ");
     String dna = scan.next();
     scan.close();
     length = dna.length();


 for(int i=0; i < length; i++) {
    ch = dna.charAt(i);

    switch (ch) {

      case 'A':   aCount++; 
                  break;
      case 'C':   cCount++;
                  break;
      case 'G':   gCount++;
                  break;
      case 'T':   tCount++;
                  break;
      default: 
         if(counter==1) { 
             System.out.println("An invalid character was entered.");
             counter++;
             //after counter is being incremented, the if statement won't be true; so no matter how invalid characters you enter, the statement will be just be printed once.
         }

    }
}

    System.out.println("A's " + aCount);
    System.out.println("C's " + cCount);    
    System.out.println("G's " + gCount);    
    System.out.println("T's " + tCount);

}

}

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