在程序JAVA中计算{和}大括号

时间:2016-03-23 04:24:45

标签: java count

我必须读取包含代码的输入文件,并生成与相应大括号({和})匹配的输出

输出的外观示例

import java.util.scanner;
public class Tester {1
 public static void main(String[] args) {2
 Scanner in = new Scanner (System.in);
 int price = in.nextInt;
 if (price < 10)
 System.out.println("Good price");
 System.out.println ("Buy it");
 }2
 }1
 }0
}0

0表示没有匹配的额外大括号。 什么是最有效的方法来解决这个问题? 我应该只使用字符串逐行处理吗?

2 个答案:

答案 0 :(得分:0)

您可以保留count。迭代每一行中的字符,分别递增(或递减)count和({1}})count{。不要忘记} close Scanner阻止或try-with-resources finally。假设您的文件Tester.java位于用户的主文件夹中,您可以执行类似的操作,

File f = new File(System.getProperty("user.home"), "Tester.java");
try (Scanner scan = new Scanner(f)) {
    int count = 0;
    while (scan.hasNextLine()) {
        String line = scan.nextLine();
        for (char ch : line.toCharArray()) {
            System.out.print(ch);
            if (ch == '{') {
                System.out.print(++count);
            } else if (ch == '}') {
                if (count > 0) {
                    System.out.print(--count);
                } else {
                    System.out.print(count);
                }
            }
        }
        System.out.println();
    }
} catch (Exception e) {
    e.printStackTrace();
}

答案 1 :(得分:0)

您可以通过使用堆栈找到额外的括号,如下所示:

public static void main(final String[] args) {

    Stack<String> stack = new Stack<String>();
    File file = new File("InputFile");
    int lineCount = 0;

    try (BufferedReader br = new BufferedReader(new FileReader(file))) {
        String line;
        while ((line = br.readLine()) != null) {
            lineCount++;
            for (int i = 0; i < line.length(); i++) {
                if (line.charAt(i) == '{') {
                    stack.push("{");
                } else if (line.charAt(i) == '}') {
                    if (!stack.isEmpty()) {
                        stack.pop();
                    } else {
                        System.out.println("Extra brace found at line number : " + lineCount);
                    }

                }
            }
        }
        if (!stack.isEmpty()) {
            System.out.println(stack.size() + " braces are opend but not closed ");
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}