Hello,
I'm a Java newbie but I am enjoying the experience so far.
I am currently stuck on what seems to be a trivial problem, but so far it has me stumped!
I'm reading in lines of text one at a time, and feeding them into a scanner to break them up into individial words. All works fine. I know need to analyse the words emitted from the scanner and check them.
My particular application permits comments in the text file, in the following form:
( this is a comment )
So an opening bracket will set a flag, such that no further text processing will occur until a closing bracket is encountered.
However, I have got stuck on the detection of the firt opening bracket. My code is not detecting it, and I can't see why. Here is the code:
package com.f3; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.Scanner; public class F3Assembler { //class level globals public F3Assembler(String inputFile) throws FileNotFoundException { BufferedReader br=null; int lineNumber=1; boolean inComment=false; String forthWord; Scanner sc; try { String sCurrentLine; br=new BufferedReader(new FileReader(inputFile)); while((sCurrentLine=br.readLine())!=null) { System.out.println("Line " + lineNumber + ": " + sCurrentLine); sc=new Scanner(sCurrentLine); while((sc.hasNext()) && (!inComment)) { forthWord=sc.next(); if(forthWord.substring(0, 0)=="(") { inComment=true; System.out.println("Comment detected; ignore rest of line"); } else { System.out.println("word: " + forthWord); } } System.out.println(""); lineNumber++; inComment=false; } } catch (IOException e) { e.printStackTrace(); } finally { try { if(br!=null) br.close(); } catch (IOException ex) { ex.printStackTrace(); } } } }
For some reason, the line:
if(forthWord.substring(0, 0)=="(") { .... }
is not triggering. I've tried various things, like:
if(forthWord=="(") { ... }
But to no avail. I've also checked the length of the strings coming in, to make sure (for example) that there isn't a trailing space or something being passed back by the scanner, but the scanner *is* working properly.
Any idea what the problem could be?
Any help/pointers greatly appreciated.
Many thanks.
--- Update ---
Ah! I think I've found it. The == operator is checking the *objects* to see if they are the same, and, of course they're not. Looks like .equals() is the one for me.
Okay, that makes sense! I'm quite enjoying this Java thing!