【发布时间】:2022-01-06 14:08:58
【问题描述】:
它在 VS Code 上运行良好,但是当我在我们的培训考试所需的编译器上运行它时,它显示了上述错误。可能是什么原因?
这是什么意思?我是编程语言的新手。所以请忽略我的错误。
import java.util.Scanner;
public class sum {
public static void main(String[] args) {
// Write solution here
int n = 0, sum = 0;
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
int arr[] = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
if (arr[0] == 0) {
System.out.println("No elements to sum");
break;
}
else if (arr[0] < 0) {
System.out.println("Invalid number of elements");
break;
}
else {
sum = sum + arr[i];
}
}
System.out.println(sum);
sc.close();
}
}
【问题讨论】:
-
@AndyTurner 怎么样?先生,我们该如何解决这个问题?
-
“怎么样?”因为它正在从扫描仪读取负数。 “我们如何解决这个问题”您需要了解传递到您的程序中的内容。我不知道。
-
条件是输入负数时显示“无效元素数”。
-
好的,所以在
n = sc.nextInt();和int arr[] = new int[n];行之间,你需要做更多的事情。