[英]Java Display 10 multiples of a number and sum them
在这个程序中,它会问你一个数字,然后显示该数字的 10 倍,然后将它们相加,但它必须是这样的:
数字 = 6;
06、12、18、24、30、36、42、48、54、60
60, 54, 48, 42, 36, 30, 24, 18, 12, 06
总和 = 324
显示数字的部分没问题,问题是我什么时候必须对它们求和。 我尝试使用列表来保存每一行的数字,然后使用第一行/列表并将其求和,但我无法让它工作。
ArrayList<Integer> i1 = new ArrayList();
ArrayList<Integer> i2 = new ArrayList();
System.out.println("Introduce un número:\n"); // Asks you a number
int n1=scan.nextInt();
int add_i = 0;
int rest_i = n1 * 11;
i1.add(add_i);
i2.add(rest_i);
while (add_i <= n1 * 9) // while add_i is less or equal to n1 * 9
{
add_i += n1; // suma n1 a i
System.out.print(i1 + " "); // Prints the result
}
System.out.println(" ");
while (rest_i >= 10) // while rest_i is greater or equal than 10
{
rest_i -= n1; // Resta n1 a i
System.out.print(i2 + " "); // Prints result
}
同样在我的程序中,mults 没有出现。
不确定您要尝试采用什么逻辑,但这似乎比
Scanner scan = new Scanner(System.in);
System.out.println("Enter number : ");
int input = scan.nextInt ();
int sum = 0;
for (int loop = 1; loop <= 10; loop++) {
int out = loop * input;
sum += out;
System.out.println(out);
}
// and down
for (int loop = 10; loop >= 1; loop--) {
int out = loop * input;
System.out.println(out);
}
System.out.println("sum is "+ sum);
尝试这个:
int sum = IntStream.iterate(startNumber, n -> n+startNumber)
.limit(10)
.peek(System.out::println)
.sum();
由于downvotes的免责声明。 这是一个替代解决方案。 我想,当您对循环有足够的了解时,您可以查看它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.