Error with my filter program
My program is doing filtering. The user input a file and the file
contains a java code with comment //, /*, */. My goal is output to a
file that the code should be without comment line;
e.g.
class ALIST { /* The given // class (the user-defined */
String name, address; // type )"
}
public class Question1{ /*The parts
in white will // be same */
public static void main( String args[ ] ) { // for all Java programs
ALIST list [ ] = new ALIST[3]; // Define an array
//for (int j=0; j<list.length; j++) {
//list[ j] = new ALIST(); // Create ALIST object
//list[ j].name = "name" + j; // Initialization
//list[ j].address = "address" + j;
list[0] = new ALIST();
list[1] = new ALIST();
list[0].name = "name0";
list[1].name = "name1";
-------------so on-------------------------
The output.txt should be:
class ALIST {
String name, address;
}
public class Question1 {
public static void main( String args[ ] ) {
ALIST list [ ] = new ALIST[2];
list[0] = new ALIST();
list[1] = new ALIST();
list[0].name = "name0";
list[1].name = "name1";
------------so on---------------------------
The // may come before /* and vice verse, so I have to check whether
ignore the whole line or only after the /* (upto */ part), /* and */
may not be in the same line
-----------------------------------------Here is my
code------------------------------------
import java.util.Scanner;
import java.io.*;
public class FilterProgram {
public static void main(String[] args){
try{
String read;
Scanner readfile = new Scanner(System.in);
read = readfile.nextLine();
File openfile = new File(read);
PrintWriter pw = new PrintWriter(new BufferedWriter(new
FileWriter("output.txt")));
if(!openfile.exists()){
throw new FileNotFoundException("File not found" +
read);
}
Scanner scanfile = new Scanner(openfile);
String tryread;
String before = null;
while((tryread = scanfile.nextLine())!=null){
int doubleslash = tryread.indexOf("//");
int block1 = tryread.indexOf("/*");
int block2 = -1;
if((doubleslash >= 0) || block1>=0){
if(doubleslash<block1){
tryread = tryread.substring(0,doubleslash);
System.out.println("doubleslash");
}
else
{
block2 = tryread.indexOf("/*");
before = tryread.substring(0,block1);
if(block2 < 0 || block2<=block1 + 1){
do{
tryread = scanfile.nextLine();
block2 = tryread.indexOf("*/");
}while(block2<0);
}
tryread = before + tryread.substring(block2 +
2);
}
System.out.println("block2 can't be reached");
}
pw.println(tryread);
}
System.out.println("here3");
readfile.close();
pw.close();
}
catch(FileNotFoundException ex){
System.err.println(ex.getMessage());
System.exit(1);
}
catch(IOException ex){
System.err.println(ex.getMessage());
System.exit(2);
}
}
}
when I type input.txt, the compiler complains:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException:
String index out of range: -1
at java.lang.String.substring(String.java:1938)
at FilterProgram.main(FilterProgram.java:35)
Java Result: 1
How can I fix it and can anyone tell the problem?