如何将它们分开,以便根据char的长度不显示多次?除了for循环之外,我还可以使用其他方法来实现我需要的输出。这是代码:
for(i=0;i <= s.length; i++){
int fc = s.length;
if(fc == 1){
System.out.println("String accepted under rule a*");
}
if(fc == 2 || fc == 4){
System.out.println("String accepted under rule a*b+");
}
if(fc >= 5 ){
System.out.println("String accepted under rule abb");
}
}
输出:
我的意思是我如何只使用一个“在规则a*b+
下接受的字符串”而不是根据数组的长度显示它。
答案 0 :(得分:1)
您可以删除循环并只使用if-else
语句
int fc = s.length;
if(fc == 1) {
System.out.println("String accepted under rule a*");
}
else
if(fc == 2 || fc == 4) {
System.out.println("String accepted under rule a*b+");
}
else
if(fc >= 5 ) {
System.out.println("String accepted under rule abb");
}
或强>
在每个break
if statement
语句
for(i=0;i <= s.length; i++) {
int fc = s.length;
//make sure that fc is not equal to 0 to avoid infinite loop
if(fc == 0) {
break;
}
if(fc == 1) {
System.out.println("String accepted under rule a*");
break;
}
if(fc == 2 || fc == 4) {
System.out.println("String accepted under rule a*b+");
break;
}
if(fc >= 5 ) {
System.out.println("String accepted under rule abb");
break;
}
}
答案 1 :(得分:1)
如果代码中的任何内容在代码的每次迭代中都没有变化,为什么还需要循环?
int fc = s.length;
if(fc == 1){
System.out.println("String accepted under rule a*");
}
if(fc == 2 || fc == 4){
System.out.println("String accepted under rule a*b+");
}
if(fc >= 5 ){
System.out.println("String accepted under rule abb");
}
或添加break
语句以终止每个if
答案 2 :(得分:-1)
int fc = s.length;
if(fc == 1){
System.out.println("String accepted under rule a*");
}
if(fc == 2 || fc == 4){
System.out.println("String accepted under rule a*b+");
}
if(fc >= 5 ){
System.out.println("String accepted under rule abb");
}