0

If I am scanning from a text

Scanner s= new Scanner("texto.txt");

// I want to compare the next char from the line with a <

// like this:

if(s.nextChar().equals("<")){
.....

I know that s.nextChar() does not exist but there is any similar thing to use in this case?

Rong Nguyen
  • 4,143
  • 5
  • 27
  • 53
  • You could loop through the input using the substring method and compare that way? That's assuming the input is not limited to 1 character – Sterling Archer Oct 09 '13 at 03:21
  • 2
    Possible duplicate of: [Scanner method to get a char](http://stackoverflow.com/questions/2597841/scanner-method-to-get-a-char) – Mr. Polywhirl Oct 09 '13 at 03:22
  • 1
    Also, for what it's worth, note that `"<"` and `'<'` are two completely different things. – Dennis Meng Oct 09 '13 at 03:22
  • so, is your question about how to do comparison of char using equals, or how to use scanner to get next char? Your title and actual question just don't match – Adrian Shum Oct 09 '13 at 03:51

3 Answers3

2

Your code would something like...

Scanner s= new Scanner("texto.txt");
s.useDelimiter("");
while (s.hasNext()) {
    if(s.nextChar()=='<'){
 .....
} 

Note that after the call of s.nextChar(), the value is actually fetched, so its better to keep the variable, if you would like to use it further, like:

char ch = s.nextChar();
Gyanendra Dwivedi
  • 5,511
  • 2
  • 27
  • 53
0

Consider dumping Scanner and using FileReader:

FileReader fileReader = new FileReader("textto.txt");

int charRead
while( (charRead = fileReader.read()) != -1)
{
   if(charRead == '<')
   {
      //do something
   }
}
lreeder
  • 12,047
  • 2
  • 56
  • 65
0
      FileReader reader = null;
  try {
     reader = new FileReader("");
     int ch = reader.read() ; 
     while (ch != -1) {
        // check for your char here
     }
  } catch (FileNotFoundException ex) {
     //
  } catch (IOException ex) {
     //
  } finally {
     try {
        reader.close();
     } catch (IOException ex) {
        //
     }
  }