Java: 保存要在循环中计算的用户输入

Java: Saving User Input to be Calculated in a Loop

很遗憾,我不能附上我的整体程序(因为它还没有完成,还有待编辑),所以我会尽力表达我的问题。

基本上,我试图保存用户输入的整数,然后将其添加到用户输入的下一个整数(在循环中)。

到目前为止,我只是尝试编写公式以查看它的工作原理,但这是一个死胡同。我需要一些东西,可以"save"用户输入的整数,当它再次循环时,可以用于计算。

以下是我正在努力实现的目标的细分:

  1. 用户输入一个整数(例如 3)
  2. 整数已保存(我不知道如何保存以及用什么保存)(例如保存3)
  3. 循环(可能是while)再次循环
  4. 用户输入一个整数(例如 5)
  5. 先前保存的整数 (3) 与这个新输入的整数 (5) 相加,得到总计 (3 + 5 =) 8。
  6. 以及更多输入、保存和添加...

您可能已经看出来了,我是 Java 的初学者。但是,我确实了解如何足够好地使用扫描仪并创建各种类型的循环(例如 while)。我听说我可以尝试使用 "var" 来解决我的问题,但我不确定如何应用 "var"。我知道 numVar,但我认为那完全是另一回事。更何况,我也想看看有没有更简单的方法可以解决我的问题?

您可以只拥有一个 sum 变量并在每次迭代时添加到它:

public static void main(String[] args) {
    // Create scanner for input
    Scanner userInput = new Scanner(System.in);

    int sum = 0;
    System.out.println("Please enter a number (< 0 to quit): ");
    int curInput = userInput.nextInt();
    while (curInput >= 0) {
        sum += curInput;
        System.out.println("Your total so far is " + sum);
        System.out.println("Please enter a number (< 0 to quit): ");
    }
}
    // This will keep track of the sum
    int sum = 0;
    // This will keep track of when the loop will exit
    boolean errorHappened = false;
    do
    {
        try
        {
            // Created to be able to readLine() from the console.
            // import java.io.* required.
            BufferedReader bufferReader = new BufferedReader(new InputStreamReader(System.in));
            // The new value is read. If it reads an invalid input
            // it will throw an Exception
            int value = Integer.parseInt(bufferReader.readLine());
            // This is equivalent to sum = sum + value
            sum += value;
        } 
        // I highly discourage the use Exception but, for this case should suffice.
        // As far as I can tell, only IOE and NFE should be caught here. 
        catch (Exception e)
        {
            errorHappened = true;
        }
    } while(!errorHappened);

您需要实施模型-视图-控制器 (mvc) 模式来处理此问题。假设您正在做一个纯 Java 应用程序而不是基于 Web 的应用程序,请查看 Oracle Java Swing Tutorial 以了解如何构建您的视图和控制器。

您的模型class非常简单。我建议只在你的控制器上制作一个 属性,它是一个 Java 整数数组列表,例如在你的控制器

的顶部
private Array<Integer> numbers = new ArrayList<Integer>();

然后你的控制器可以有一个public方法来添加一个数字并计算总数

public void addInteger(Integer i) {
     numbers.addObject(i);
}
public Integer computeTotal() {
   Integer total = 0;
   for (Integer x : numbers) {
      total += x;
   }
   return total;
}

好的,所以你想要存储一个数字。

因此考虑将其存储在变量中,比如 loopFor

loopFor = 3

现在我们再次要求用户输入。

然后我们将它添加到 loopFor 变量中。

所以,我们可能会使用 scanner 输入,任何东西都可以使用,Scanner 是读取数字的更好选择。

Scanner scanner = new Scanner(System.in);//we create a Scanner object
int numToAdd = scanner.nextInt();//We use it's method to read the number.

所以总结一下。

int loopFor = 0;
Scanner scanner = new Scanner(System.in);//we create a Scanner object

do {
    System.out.println("Enter a Number:");
    int numToAdd = scanner.nextInt();//We use it's method to read the number.
    loopFor += numToAdd;
} while (loopFor != 0);