I am new to programming and I am trying to create a program which parses a file and outputs the tokens. At the minute I am trying to create an if statement which will output the name of each operator with two characters, eg "&&" or "<=". My if statement does not work for "<=" as it picks up the '<" and '=' separately due to the earlier code:
else if (getOp(ch) != null) {
System.out.println(line + ", " + sglchar + ", "+ ch);
counter++;
continue;
}
My getOp(ch) method contains the operators with one character, however I cannot figure out how to do this with two character operators and my if statements don't seem to be doing the trick.
This is the if statement I am trying:
else if (prog.charAt(counter) == '<' && prog.charAt(counter+1) == '=') {
String str = "";
str += ch;
str += prog.charAt(counter++);
System.out.println(line + ", " + getOp(str) + ", " + str);
counter++;
continue;
}
As outlined in my comments, use of Java's Scanner class. It makes parsing text files very easy.
Consider the following:
Scanner sc = new Scanner(new File("file.txt"));
while (sc.hasNext()) {
String token = sc.next();
if (Pattern.matches("<=", token)) {
System.out.println(token);
}
}
sc.close();
}
outputs:
<=
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.