因此,我有一个循环,它将一行文本并将其设置为要由方法处理的字符串。

while (input.hasNextLine()){
    String text = input.nextLine();
    processLine(text);
}


processLine方法是。

public static void processLine(String text) {
    Scanner data = new Scanner(text);
    while (data.hasNext()){
        String str = "hi";
        int tabCount = 0;
        str = data.next();
        System.out.print(str + " ");
        if (str.equals("{")) {
           tabCount++;
           System.out.println();
           for (int i = 0; i < TAB_SIZE * tabCount; i++){
              System.out.print(" ");
        }
    }
}


发生的事情是我的tabCount没有增加,但仍在执行println。怎么会这样?这是输出。

public class Test1 {
    public static void main( String[] args ) {
    System.out.println( "This is Test 1." ); } }


任何帮助表示赞赏。

最佳答案

tabCount变量位于while loop内部,因此每次迭代都会将其重置,即始终为0

尝试

public static void processLine(String text) {
    Scanner data = new Scanner(text);
    int tabCount = 0;
    while (data.hasNext()){
        String str = "hi";
        str = data.next();
        System.out.print(str + " ");
        if (str.equals("{")) {
           tabCount++;
           System.out.println();
           for (int i = 0; i < TAB_SIZE * tabCount; i++){
              System.out.print(" ");
        }
    }
}

09-10 01:00
查看更多