I'm trying to create a program that takes a file as an input and then counts the number of comments in that file. I've created a switch case to do so.
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);
}
The issue here is that it works up to 1 comment in the code. For example, if no comments exist the output would be:
#include <stdio.h>
int main()
{
int marks, i, num;
}
Number of comments: 0
If 1 exists:
#include <stdio.h>
int main()
{
/* comment */
int marks, i, num;
}
Number of comments: 1
If 2 exist:
#include <stdio.h>
int main()
{
/* comment */
/* comment 2 */
int marks, i, num;
}
Number of comments: 1
The issue being that it seems to be exiting my switch case as soon as it finds the first one. Is there a way to cycle this case back into the loop and start it all over again?
CodePudding user response:
The issue with your approach is when the state is set to 4 ... which is when a comment block is detected. Instead, you should replace state = 4 with state = 0 in block of case 3.
CodePudding user response:
After counting the first comment, your code is missing that state resetting logic in 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);
}