I am trying to print any string literals I have in a file I am reading using a scan method. I am limited to follow a guide as to the structure of my programme, by my professor.
Currently, I have this section of code that is printing string literals, or is trying to:
public static void scan (String prog) {
int n = prog.length();
int index = 0;
int lineNumber = 1;
while (index < n) {
char ch = prog.charAt(index);
boolean whiteSpace = isWhiteSpace(ch);
boolean newLine = isLineBreak(ch);
TokenType sym = getSymbol(ch);
TokenType op = getOp(ch);
boolean letter = isLetter(ch);
boolean digit = isDigit(ch);
// start of if statement preceding this point
else if (ch == '\"') {
String str = "";
str += ch;
index++;
while (index < n) {
ch = prog.charAt(index);
if (ch != '\"') {
str += ch;
index++;
}
else break;
}
System.out.println(lineNumber + "," + TokenType.STRING + ", " + str);
index++;
continue;
}
else {
System.out.println("Encountered something not expected: " + ch);
index++;
continue;
}
This outputs the first " and all the characters before the next " but not the last " of the string literal itself. How can I go about changing this code to print the whole string literal?
Current output:
11, STRING, "This just random code
What I need:
11, STRING, "This just random code"
Aucun commentaire:
Enregistrer un commentaire