I have an assignment question that asks us, given a test phrase,
// the first comment
public class Test {
// another comment
public static void main( String[] args ) { // the main method
String slashes = "//"; // ignore // in quotes
System.out.println( slashes + " hi " + slashes );
} // end of main
}
^ Test Phrase
We have to go through the code and remove all the 1 line comments. Taking what was given as an aid to the problem i modified to look like this
import java.io.IOException;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.Reader;
public class RemoveLineComments {
public static boolean skipPast( Reader rd, String end )
throws IOException
{
int matched = 0;
int ch;
while( (ch=rd.read()) != -1 ) {
char c = (char)ch;
if ( c == end.charAt(matched) ) {
matched++;
if ( matched == end.length() ) {
return true;
}
}
else {
matched = 0;
}
}
return false;
}
public static void main( String[] args ) throws IOException {
if( args.length != 1 ) {
System.out.println("usage: java RemoveComments infile");
System.exit( 1 );
}
BufferedReader rd =
new BufferedReader( new FileReader( args[0] ));
int ch;
while( (ch=rd.read()) != -1 ) {
char c = (char)ch;
if ( c == '/' ) {
ch = rd.read();
if ( ch == -1 ) {
System.out.print( '/' );
break;
}
c = (char)ch;
if ( c == '/' ) {
if ( ! skipPast( rd, " " ) ) break;
}
else {
System.out.print( '/' );
System.out.print( c );
}
}
else {
System.out.print( c );
}
}
System.out.flush();
}
}
However, i'm having some trouble making it look like i want it to. Right now i have the code so that it finds a double space and stops, So, my question is this, is there a way so that i will stop when it gets to the end of a line, and still print it properly
public class Test {
public static void main( String[] args ) { // the main method
String slashes = "//";
System.out.println( slashes + " hi " + slashes );
}
}
^That's the proper way.