gpt4 book ai didi

Java:使用堆栈检查括号的正确性

转载 作者:行者123 更新时间:2023-12-02 11:43:35 25 4
gpt4 key购买 nike

在这个程序中,我试图检查输入字符串中的括号是否平衡。例如,(9*[3+4]) 是正确的,而 {10/[4+9) 则不正确。但是,每当我尝试运行我的程序并输入输入时。

很多问题都出现了。当我输入字符串 ([{}]) 时,它会说括号不平衡,当我输入 ([]) 时,它会给我一个空堆栈异常(exception)。我对堆栈的概念相当陌生,所以我在这方面遇到了很多麻烦。

import java.io.*;
import java.util.*;
import java.util.Stack;

public class BracketCheck {
public static void main(String args[]) {
Stack stk = new Stack();
Scanner s = new Scanner(System.in);
boolean balance = true;

System.out.println("Enter a string");
String str = s.nextLine();

for(int i = 0; i < str.length(); i++) {
if(str.charAt(i) == '(' || str.charAt(i) == '['
|| str.charAt(i) == '{') { //if the char is an opening bracket then add to stack
stk.push(str.charAt(i));
}
else if(str.charAt(i) == ')' || str.charAt(i) == ']' ||
str.charAt(i) == '}') { //if char is a closing bracket
if(!stk.isEmpty()) {
System.out.println(stk.peek()); // to check if the bracket was added
if((stk.pop().equals('(') && str.charAt(i) != ')') ||
(stk.pop().equals('[') && str.charAt(i) != ']') ||
(stk.pop().equals('{') && str.charAt(i) != '}')) {
// this is where i believe the empty stack exception occurs
balance = false;
System.out.println("Brackets don't match");
break;
}
}
else { // flase because there is no opeing bracket to match with the closing bracket
balance = false;
System.out.println("There is no opening bracket");
break;
}
}
}
if (balance == true) {
System.out.println("The equation is balanced");
}
else {
System.out.println("The equation is not balanced");
}
}
}

最佳答案

问题是你一直打电话stk.pop()当您检查括号是否匹配时。

if((stk.pop().equals('(') && str.charAt(i) != ')') ||
(stk.pop().equals('[') && str.charAt(i) != ']') ||
(stk.pop().equals('{') && str.charAt(i) != '}')) {

弹出一次,存储在变量中,使用该变量而不是 stk.pop()在这种情况下。

Character pop = stk.pop();
if((pop.equals('(') && str.charAt(i) != ')') ||
(pop.equals('[') && str.charAt(i) != ']') ||
(pop.equals('{') && str.charAt(i) != '}')) {

您还可以使用原语 char作为 pop 的类型,只需使用简单的 == ,例如char pop = stk.pop(); if (pop == '(' || ... .

<小时/>

正如我在上面的评论中指出的,您可以使用字符串检查字符是否在字符列表中:

if ("([{".indexOf(str.charAt(i)) >= 0) { ... }

您也可以在匹配检查中使用它:

int idx = ")]}".indexOf(str.charAt(i));
if (idx >= 0 && "([{".charAt(idx) != pop) {
// They don't match!
}

关于Java:使用堆栈检查括号的正确性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48370745/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com