在读取文件时使用扫描程序检查重复模式并使用hasNext()和hasNextInt()

时间:2015-10-07 14:33:13

标签: integer pattern-matching java.util.scanner token file-read

我想检查包含以下内容的文本文件的输入:

task1 2 3 task2 2 3 task3 2 3 task4 4 5 task5 4 5
task6 7 9 task7 7 9 task8 7 9 task9 7 9
task10 7 9 task11 7 9 task12 7 9 task13 7 9
task14 7 9 task15 7 9 task16 10 11 task17 10 11
task18 10 11 task19 10 11  task20 10 12

我尝试了以下代码,但它不起作用,不确定有什么问题,以及如何继续使用Scanner的hasNext()和hasNextInt()来检查内容,使其以非整数,例如字母数字字符的task1,后跟2个整数,然后在整个文件中重复这种格式,如上所示。

Scanner s;
try {
    s = new Scanner(readFile); // create new Scanner scanning file and references variable s to it
    while (s.hasNext()) { // when there is the next string separated by default whitespace

        // check whether contents of file follow the right format
        if (!s.hasNextInt()) { // if s.next() is not an integer
            while (s.hasNext()) {
                if (s.hasNextInt()) { // if s.next() that follows is an integer
                    while (s.hasNext()) {
                        if (s.hasNextInt()) { // if s.next() that follows is an integer
                            System.out.println("The content of the file follows the right format.");
                            break;
                        }
                    }
                }
            }

        } else { // if s.next() does not follow right format
            System.out.println("The content of the file does not follow the right format.");
            break;  
        }   

    }
s.close();
}

1 个答案:

答案 0 :(得分:0)

您必须实际将扫描仪移动到文件中。 使用s.next()在文件中前进。由于您正在寻找" string int int",因此不需要在代码中多次使用while(s.hasNext)

我会把它变成这样的函数:

public boolean isCorrectFormat(readFile){
    Scanner s;
    try {
        s = new Scanner(readFile);
        while (s.hasNext()) { 
                if (!s.hasNextInt()) {                  //If next is not an integer
                        s.next();                       //Move forward
                        if (s.hasNextInt()) {           //If next is an integer
                                s.next();               //Move forward
                                if (!s.hasNextInt()) {  //If s.next() is NOT 
                                                        //an integer, then the 
                                                        //pattern is NOT good
                                        s.close();      //Close the scanner 
                                        return false;   //and return false.
                                }                       //Else it will just continue
                        }
                }
        }
        s.close();
        return true;    //If it went through the loop without issues, 
                        //then the pattern is good.
    }catch(Exception e){
          //do stuff
    }final{
          s.close(); //always
    }
}