在while循环中存储多个值- Java

  • 本文关键字:Java 存储 while 循环 java
  • 更新时间 :
  • 英文 :


我试图将2个数字的总和存储在while循环中,以便一旦循环结束,多个总和可以相加并作为总和给出,但是我对Java相当陌生,我不确定如何去做这件事。我试图使用一个数组,但我不确定它是否是正确的东西使用。如有任何帮助,我将不胜感激。

import java.util.Scanner;
public class StoredWhile{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int TotalNum[]=new int[10];
Int Num1, Num2, AddedNum;
String answer;
do{
System.out.println("Please enter a number");
Num1 = input.nextInt();
System.out.println("Please enter a second number");
Num2 = input.nextInt();
AddedNum = Num1 + Num2;
System.out.println("The sum of the two entered numbers is " + AddedNum);
TotalNum[0]=AddedNum;
TotalNum[1]=;
System.out.println("Would you like to calculate the sum of two more numbers (y/n)?");
answer = input.next();
}
while (answer.equals("y"));
System.out.println("The total sum of all the numbers you entered is " + TotalNum);
}
}

有一个名为ArrayList<>的数据容器。它是动态的,您可以根据需要添加任意数量的总和。

你的例子可以这样实现:

public class StoredWhile{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
ArrayList<Integer> listOfSums = new ArrayList<>();
int Num1, Num2, AddedNum;
String answer;
do{
System.out.println("Please enter a number");
Num1 = input.nextInt();
System.out.println("Please enter a second number");
Num2 = input.nextInt();
AddedNum = Num1 + Num2;
System.out.println("The sum of the two entered numbers is " + AddedNum);
listOfSums.add(AddedNum);
System.out.println("Would you like to calculate the sum of two more numbers (y/n)?");
answer = input.next();
}
while (answer.equals("y"));
// Then you have to calculate the total sum at the end
int totalSum = 0;
for (int i = 0; i < listOfSums.size(); i++) 
{
totalSum = totalSum + listOfSums.get(0);
}
System.out.println("The total sum of all the numbers you entered is " + totalSum);
}
}

从我看到的,你来自c#的背景(因为我看到所有变量的大写字母命名)。尽量遵循java标准的命名和一切,它将帮助您融入社区,使您的代码更容易被java开发人员理解。

有几种方法可以实现你想要的,我试图解释最简单的。要了解更多关于ArrayList,请查看这个小教程。

祝你好运!

array:

import java.util.Scanner;
public class StoredWhile{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int TotalNum[]=new int[10];
int Num1, Num2, AddedNum;
String answer;
int count = 0;
do{
System.out.println("Please enter a number");
Num1 = input.nextInt();
System.out.println("Please enter a second number");
Num2 = input.nextInt();
AddedNum = Num1 + Num2;
System.out.println("The sum of the two entered numbers is " + AddedNum);

TotalNum[count]=AddedNum;
count++;


System.out.println("Would you like to calculate the sum of two more numbers (y/n)?");
answer = input.next();
}
while (answer.equals("y"));
int TotalSum = 0;
for(int i = 0; i <count; i++ ) {
TotalSum += TotalNum[i];
}
System.out.println("The total sum of all the numbers you entered is " + TotalSum);
}
}

这个解决方案不是动态的。在开始时定义的数组长度可能不够大。

最新更新