Compare a char using equals

前端 未结 3 962
悲哀的现实
悲哀的现实 2021-01-28 21:53

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 <

相关标签:
3条回答
  • 2021-01-28 22:04
          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) {
            //
         }
      }
    
    0 讨论(0)
  • 2021-01-28 22:24

    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();
    
    0 讨论(0)
  • 2021-01-28 22:27

    Consider dumping Scanner and using FileReader:

    FileReader fileReader = new FileReader("textto.txt");
    
    int charRead
    while( (charRead = fileReader.read()) != -1)
    {
       if(charRead == '<')
       {
          //do something
       }
    }
    
    0 讨论(0)
提交回复
热议问题