gpt4 book ai didi

java - 如何验证这些表达式是否有效(所有括号配对 - 闭合)?

转载 作者:行者123 更新时间:2023-12-01 19:29:50 25 4
gpt4 key购买 nike

这是我的第三次尝试,但预期结果不正确。

第一个表达式应该打印 -Bracket is Balanced。第二个表达式应该打印 -Bracket is NOT Balance.

注意需要使用 - charAt要解决的子字符串,而不是数组或堆栈!因为我还没有学习这些!

import java.lang.*; 
import java.util.Scanner;


public class CheckBracketsPairs {
public static void main(String[] args) {
validateExpresion("(4+4)");
validateExpresion("(4+4)*1)");
}

public static void validateExpresion(String s) {

// MY CODES BELOW
int count = 0;
String open = "(";
String close = ")";

for (int i = 0, n = s.length(); i < n; i++) {
Character c = s.charAt(i);

if(c.equals(open)) {
count++;
}

if(c.equals(close)) {
count--;
}
}

if(count == 0) {
System.out.println("\n Expression: " + s + ", -Bracket is balanced");
} else {
System.out.println("\nBracket is NOT balanced");
}
}
}

最佳答案

这里再次尝试。最后一行未按预期显示结果。
应该是 - -支架不平衡

public class CheckBracketsPairs  {
public static void main(String[] args) {
validateExpression(")((5+9)-2)");
validateExpression("(2*6)-1)*(2^2)");
validateExpression("(8^2)");
validateExpression("(5+8^2))"); // This line computing?
validateExpression("(5+8^2)("); // Why is this line NOT computing?
}

public static void validateExpression(String s) {

// MY CODES BELOW
int count = 0;
char open = '(';
char close = ')';

for (int i = 0, n = s.length(); i < n; i++) {
char c = s.charAt(i);

if(c == open) {
count++;
}

if (c == close) {
count--;
// If statement to check for closed brackets
if (count < 0) {
System.out.println("\nExpression: " + s + " -Bracket is NOT balanced");
break;
}
}
}

if (count == 0) {
System.out.println("\nExpression: " + s + " -Bracket is balanced");
}
}
}

关于java - 如何验证这些表达式是否有效(所有括号配对 - 闭合)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60094899/

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