我目前正在尝试找出如何获取用户在对话框中输入的数字并将其放入数组中,以便计算所有数字的总和。我目前只需要总和方面的帮助,而不需要底部产品的帮助。我只能更改 sums() 方法内部的内容。
这是我到目前为止在 sums() 中的内容,但当我输入时它没有显示任何内容。我应该输入无限数量的数据,然后在用户点击 0 时停止。对话框输入有效,但我不知道如何使用使用单个参数的方法来执行此操作。非常感谢任何帮助!
int sum = 0;
int counter = 1;
while(counter > 1) {
int[] numberArray = new int[counter];
(numberArray[counter]) = number;
sum = sum + number;
System.out.println(sum);
counter = counter + 1;
}
// int counter = 0;
// int[] numm = new int[counter];
// (numm[counter]) = number;
这是带注释的代码:
// SumAndProduct.java - This program computes sums and products.
// Input: Interactive.
// Output: Computed sum and product.
import javax.swing.*;
public class SumAndProduct
{
public static void main(String args[])
{
int number;
String numberString;
numberString = JOptionPane.showInputDialog("Enter a positive integer or 0 to quit: ");
number = Integer.parseInt(numberString);
while(number != 0)
{
// call sums() method here
sums(number);
// call products() method here
products(number);
numberString = JOptionPane.showInputDialog("Enter a positive integer or 0 to quit: ");
number = Integer.parseInt(numberString);
}
System.exit(0);
} // End of main() method.
// Write sums() method here.
public static void sums(int number) {
//sums
}
// Write products() method here.
public static void products(int number) {
// products
}
}
// End of SumAndProduct class.
最佳答案
只需声明两个静态成员来保存总和和乘积,以便您可以从方法内部访问它们。
public class SumAndProduct
{
private static long sum = 0;
private static long product = 1;
public static void sums(int number) {
sum += number;
}
public static void products(int number) {
product *= number;
}
}
关于java - 无法获取数组并将其求和 - 输入是通过 java 对话框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50007530/