誰能告訴我如何編寫一個程序,我必須從文本文件中讀取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