简体   繁体   中英

Can't figure out what is wrong with my Brackets_checker program

When I try to compile with Eclipse I have next errors:

Exception in thread "main" java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Scanner.java:907)
    at java.util.Scanner.next(Scanner.java:1416)
    at scanner_io.Brackets_checker.main(Brackets_checker.java:21)
package scanner_io;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Scanner;

public class Brackets_checker {

  public static void main(String[] args) {
    int k = 0;
    Scanner sc;
    char c ;
    boolean open = false;
    try {
      sc = new Scanner(new FileReader("data.txt"));
      int i = 0;
      c = sc.next().charAt(i);
      while (c != '\n') {
        c = sc.next().charAt(i);

        if (c == '(') {
          k++;
          open = true;
        }
        if (c == ')' && open == true) {
          k--;
          open = false;
        }

        i++;
      }

      sc.close();
      if (k == 0)
        System.out.println("OK !");
      else
        System.out.println("NOT OK !");
    } catch (FileNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

  }
}

Scanner#next() keeps eating elements, and you are getting a new element each time you invoke c = sc.next().charAt(i);

This means that if you have for example the tokens Test is going wrong , you will produce the characters that will be assigned to c : T, s, i, n - this is NOT what you are after most likely.

Instead, have a String variable currentToken , and iterate on its characters:

For example:

String currentToken = sc.next()
for (int i = 0; i < currentToken.length(); i++) {
    c = currentToken.charAt(i)
}

You should also use Scanner#hasNext() before invoking next() , it's safer, also verify your returned String ( currentToken in above example) is not null .

this is wrong:

c = sc.next().charAt(i);

You read a String from the file and get the i'th character from it. The next time you call c = sc.next().charAt(i) , you get the i'th character of the next String, which means you only read one character from each String and skip all the rest.

You should store sc.next() in a String variable and iterate over the characters of that String before you call sc.next() again.

And c != '\\n' is not a good stopping condition. You should check instead if the last call to sc.next() returned null.

Come to think of it, if you expect your entire input to be in one line, just call String s = sc.nextLine(); one time and process the characters of s .

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM