谁能告诉我如何编写一个程序,我必须从文本文件中读取ac程序,然后计算if-else语句的数量,不包括嵌套if-else。 在这个程序中,我已经计算了if和else从一个文本文件的数量,但是如何从这个计数中排除嵌套if? 请帮我。计数的if和else排除嵌套if-else的数量
package softwaretesting;
import java.io.*;
import java.util.Scanner;
public class SoftwareTesting {
public static void main(String[] args) throws IOException {
int countIf = 0, countElse = 0;
Scanner input;
input = new Scanner(System.in);
String fileName;
System.out.println("Enter the path of the file from which no of if and else statements are to be counted");
fileName = input.next();
Scanner file;
file = new Scanner(new File(fileName));
int count=0;
while (file.hasNextLine())
{
String line = file.nextLine();
if (line.indexOf("if") != -1 && count%2==0)
{
countIf++;
}
if (line.indexOf("else") != -1 )
{
countElse++;
}
}
{
System.out.println("No of If statements: " + countIf);
System.out.println("No of Else statements: " + countElse);
}
}
}
提示:计算括号。 –
我确实尝试过,但是如果在声明中只有一行我们不使用大括号,那么通常情况下该怎么办? – Aiman
你需要在某个地方保持某种状态。这意味着如果您目前处于if区块中,请跟踪。布尔值可以正常工作。另外,不要假设你不会在单行 – crush