JAVA程序中{和}大括号的计数
我必须读取包含代码的输入文件,并生成与相应大括号({和})匹配的输出 输出外观的示例JAVA程序中{和}大括号的计数,java,count,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
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
import java.util.scanner;
公共类测试器{1
公共静态void main(字符串[]args){2
扫描仪输入=新扫描仪(系统输入);
整数价格=in.nextInt;
如果(价格<10)
System.out.println(“好价格”);
System.out.println(“购买”);
}2
}1
}0
}0
0将表示没有匹配项的额外大括号。
最有效的方法是什么?
我应该用字符串逐行处理吗 您可以保留
计数
。迭代每行中的字符,分别为{
和}
增加(或减少)计数和(输出计数)。不要忘记用最后一个块或一个按钮关闭扫描仪。假设您的文件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();
}
您可以使用堆栈找到额外的大括号,如下所示:
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();
}
}
publicstaticvoidmain(最终字符串[]args){
堆栈=新堆栈();
文件文件=新文件(“输入文件”);
int lineCount=0;
try(BufferedReader br=new BufferedReader(new FileReader(file))){
弦线;
而((line=br.readLine())!=null){
lineCount++;
对于(int i=0;i
你能展示一下你的方法吗?虽然这个问题对我来说还不够清楚。检查大括号最简单的方法是使用堆栈。1-当你找到左大括号时,推它2-当你找到右大括号时,从堆栈中弹出一个项目。如果完成处理后堆栈为空,那么你就有了正确的大括号数。所以我的初始思考的过程是我用Strings.so逐行地去做,(input.hasNextLine()){String line=input.nextLine();if line.contains(“{”){Counter++;}if line.contains(“}”){Counter-->}想法是用所有的{大括号增加计数器,然后用}减小它大括号。请使用post edit将您的想法放在问题中,而不仅仅是评论它,特别是对于许多代码。您能向我解释一下(char ch:line.tocharray())的作用吗?这是返回的char[]
。谢谢您的帮助,我没想到它会这么简单,我想我需要一些阅读。