[英]Java- For loop with a switch statement containing default case. How can I get the default case to print the output only once?
以下默认语句完全符合其预期的目的:捕获上述情况中未提及的所有字符,并通知我(在运行字符串之后)在其中某处输入了无效字符。 但是,如果有两个无效字符:println语句将打印两次。 如果有3次:3次,等等。在100,000个字符的字符串中,多次打印该行效率不高。
无论输入了多少个无效字符,我如何都能使其仅打印一次? 请提供建议并预先感谢您对Java新手的帮助!
//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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.