使用堆栈检查.txt文件中的(、、 {、、 [等,等等-Java [英] Use a stack to check .txt file for ('s, {'s, ['s, etc - Java
问题描述
我正在尝试用Java编写一种方法来搜索我导入的文本文件中的特定字符.该文件实际上是我设计并转换为 .txt
文件的Java程序.
I am trying to write a method in java to search a text file that I imported for specific characters. The file is actually a java program that I designed and converted to a .txt
file.
找到打开的花括号/括号时,我应该将其添加(推入)堆栈中,然后找到对应的关闭的花括号/括号时,我应该将其从栈中移除(弹出).
When an opening brace/bracket is found, I am supposed to add (push) it to a stack and then when a corresponding closing brace/bracket is found I am supposed to remove (pop) it from the stack.
目的是查看我是否有正确数量的)
,}
,]
和>
与(
, {
, [
和>
返回true,否则返回false.
The purpose is to see if I have the correct amount of )
, }
, ]
and >
to correspond with the (
, {
, [
and >
. If they all match up the method should return true, if they don't it should return false.
有人知道我该怎么写吗?
Anyone know how I can write this?
推荐答案
这是用于平衡输入文本文件中括号的示例实现
This is the sample implementation for balancing the brackets in a input text file
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Stack;
public class BalanceBrackets {
private Stack<Character> symbolStack;
public void balance(String inputText) {
symbolStack = new Stack<Character>();
for (int index = 0; index < inputText.length(); index++) {
char currentSymbol = inputText.charAt(index);
switch (currentSymbol) {
case '(':
case '[':
case '{':
symbolStack.push(currentSymbol);
break;
case ')':
case ']':
case '}':
if (!symbolStack.isEmpty()) {
char symbolStackTop = symbolStack.pop();
if ((currentSymbol == '}' && symbolStackTop != '{')
|| (currentSymbol == ')' && symbolStackTop != '(')
|| (currentSymbol == ']' && symbolStackTop != '[')) {
System.out.println("Unmatched closing bracket while parsing " + currentSymbol + " at " + index+1);
return;
}
} else {
System.out.println("Extra closing bracket while parsing " + currentSymbol + " at character " + index+1);
return;
}
break;
default:
break;
}
}
if (!symbolStack.isEmpty())
System.out.println("Insufficient closing brackets after parsing the entire input text");
else
System.out.println("Brackets are balanced");
}
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new FileReader("D://input.txt"));
String input = null;
StringBuilder sb = new StringBuilder();
while ((input = in.readLine()) != null) {
sb.append(input);
}
new BalanceBrackets().balance(sb.toString());
}
}
这篇关于使用堆栈检查.txt文件中的(、、 {、、 [等,等等-Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!