我正在嘗試創建一個程式,該程式將檔案作為輸入,然后計算該檔案中的評論數。為此,我創建了一個開關盒。
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws FileNotFoundException {
String file = new Scanner(new
File("file")).useDelimiter("\\Z").next();
int length, state, i, j;
state = 0;
i = 0;
j = 0;
while (i < file.length()) {
switch (state) {
case 0:
if (file.charAt(i) == '/') {
state = 1;
i ;
} else i ;
break;
case 1:
if (file.charAt(i) == '*') {
state = 2;
i ;
} else i ;
break;
case 2:
if (file.charAt(i) == '*') {
state = 3;
i ;
} else i ;
break;
case 3:
if (file.charAt(i) == '/') {
state = 4;
i ;
j ;
} else {
state = 2;
i ;
}
break;
case 4:
i ;
break;
default:
String nothing = "nothing";
}
}
System.out.println("Number of comments " j);
}
這里的問題是它在代碼中最多可以使用 1 條評論。例如,如果不存在評論,則輸出將是:
#include <stdio.h>
int main()
{
int marks, i, num;
}
Number of comments: 0
如果 1 存在:
#include <stdio.h>
int main()
{
/* comment */
int marks, i, num;
}
Number of comments: 1
如果存在 2:
#include <stdio.h>
int main()
{
/* comment */
/* comment 2 */
int marks, i, num;
}
Number of comments: 1
問題是它似乎一找到第一個開關盒就退出了我的開關盒。有沒有辦法將這種情況回圈回回圈并重新開始?
uj5u.com熱心網友回復:
您的方法的問題是當狀態設定為 4 時......這是檢測到評論塊的時候。相反,您應該在案例 3 的塊中將 state = 4 替換為 state = 0。
uj5u.com熱心網友回復:
在計算第一條評論后,您的代碼缺少.case 4
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws FileNotFoundException {
String file = new Scanner(new
File("file")).useDelimiter("\\Z").next();
int length, state, i, j;
state = 0;
i = 0;
j = 0;
while (i < file.length()) {
switch (state) {
case 0:
if (file.charAt(i) == '/') {
state = 1;
i ;
} else i ;
break;
case 1:
if (file.charAt(i) == '*') {
state = 2;
i ;
} else i ;
break;
case 2:
if (file.charAt(i) == '*') {
state = 3;
i ;
} else i ;
break;
case 3:
if (file.charAt(i) == '/') {
state = 4;
i ;
j ;
} else {
state = 2;
i ;
}
break;
case 4:
i ;
state = 0;
break;
default:
String nothing = "nothing";
}
}
System.out.println("Number of comments " j);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/511797.html
標籤:爪哇循环文件输入开关语句
