gpt4 book ai didi

java - 在 Java 中将程序作为命令行参数运行时出现错误,如何解决此问题?

转载 作者:行者123 更新时间:2023-12-01 06:49:54 24 4
gpt4 key购买 nike

当我尝试在 Eclipse 中将这个程序作为命令行参数运行时,出现错误。错误内容如下:

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

当我将 main 方法更改为 String 时,我无法调用第二个方法,因为 String main 方法与 int returnSum 方法不兼容。

我需要根据要求将 returnSums 方法设置为 int 类型方法,但我不知道如何在不出现错误的情况下执行此操作。它在要求中说我需要为该方法使用可变数量的参数,但很难理解这个想法。

有人可以帮我解决这个问题吗?这是我的代码:

public static void main(int[] args) {

// Printing the entered digits
System.out.print("Passing");
System.out.print(" [ ");

for (int nums = 0; nums < args.length; nums++) {
System.out.print(args[nums] + " ");

}
System.out.print("] ");
System.out.println("\nSum is " + returnSum(args)); // Calling on the second method for the sum

}
// Taking the nums from the main method as arguments
public static int returnSum(int...args) {
int sum = 0;
// Calculating the sum
for (int nums = 0; nums < args.length; nums++) {
sum = sum + nums;
}
return sum;

}

谢谢!

最佳答案

尝试下面的代码:

public class SumOfNumbers {
public static void main(String[] args) {

int[] intArgs = new int[args.length];
for (int x = 0; x < args.length; x++) {
if (args[x].matches("\\d+")) {
intArgs[x] = Integer.parseInt(args[x]);
} else {
System.out.println(args[x] + " is not a Integer hence skiped in this program");
}
}

// Printing the entered digits
System.out.print("Passing");
System.out.print(" [ ");

for (int nums = 0; nums < intArgs.length; nums++) {
System.out.print(intArgs[nums] + " ");

}
System.out.print("] ");
System.out.println("\nSum is " + returnSum(intArgs)); // Calling on the second method for the sum

}

// Taking the nums from the main method as arguments
public static int returnSum(int... args) {
int sum = 0;
// Calculating the sum
for (int nums = 0; nums < args.length; nums++) {
sum = sum + args[nums];
}
return sum;
}
}

关于java - 在 Java 中将程序作为命令行参数运行时出现错误,如何解决此问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37756058/

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