gpt4 book ai didi

java - 如何运行这部分代码?

转载 作者:太空宇宙 更新时间:2023-11-04 12:56:18 24 4
gpt4 key购买 nike

我在堆栈上找到了这段代码,我想在我的机器上尝试一下,但它一直给我一个错误

Main 类中未找到 Main 方法,请将 main 方法定义为: 公共(public)静态无效主(字符串[]参数)或者 JavaFX 应用程序类必须扩展 javafx.application.Application

谁能帮我想想该怎么办?这是我想在我的机器上尝试的代码部分

public static void main(String[] args) {

}
public int parse(String input) {
Scanner scanner = new Scanner(input);

return consumeLine(scanner);
}

public int consumeLine(Scanner scanner) {
if( scanner.hasNext("(") ) {
return consumeExpression(scanner);

} else if( scanner.hasNext("IF") ) {
return consumeIf(scanner);
}
return 0;
}


public int consumeExpression(Scanner scanner) {
scanner.next("(");
int a = scanner.nextInt();
int b = scanner.nextInt();
String op = scanner.next("[+-/*]");
scanner.next(")");

if( "+".equals(op) ) {
return a + b;

} else if( "-".equals(op) ) {
return a - b;
}

throw new RuntimeException("parsing error");
}

public int consumeIf(Scanner scanner) {
scanner.next("IF");
int exp1 = consumeExpression(scanner);
int exp2 = consumeExpression(scanner);
int exp3 = consumeExpression(scanner);
int exp4 = consumeExpression(scanner);

if( exp1 < 0 ) {
return exp2;
} else if( exp1 == 0 ) {
return exp3;
}

throw new RuntimeException("should not be here (TM)");
}

最佳答案

试试这个。

    public int parse(String input) {
Scanner scanner = new Scanner(input);
return consumeLine(scanner);
}

public int consumeLine(Scanner scanner) {
if( scanner.hasNext("\\(") ) {
return consumeExpression(scanner);
} else if( scanner.hasNext("IF") ) {
return consumeIf(scanner);
}
return 0;
}


public int consumeExpression(Scanner scanner) {
scanner.next("\\(");
int a = scanner.nextInt();
int b = scanner.nextInt();
String op = scanner.next("[+-/*]");
scanner.next("\\)");

if( "+".equals(op) ) {
return a + b;

} else if( "-".equals(op) ) {
return a - b;
}

throw new RuntimeException("parsing error");
}

public int consumeIf(Scanner scanner) {
scanner.next("IF");
int exp1 = consumeExpression(scanner);
int exp2 = consumeExpression(scanner);
int exp3 = consumeExpression(scanner);
int exp4 = consumeExpression(scanner);

if( exp1 < 0 ) {
return exp2;
} else if( exp1 == 0 ) {
return exp3;
}

throw new RuntimeException("should not be here (TM)");
}

示例输出

System.out.println(parse(" IF ( 0 0 - ) ( 1 1 + ) ( 2 2 + ) ( 3 3 + )"));
// -> 4

关于java - 如何运行这部分代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35353310/

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