On this program, it asks you a number, then displays 10 multiples of that number and then sums them but it has to be like this:
Number = 6;
06, 12, 18, 24, 30, 36, 42, 48, 54, 60
60, 54, 48, 42, 36, 30, 24, 18, 12, 06
Sum = 324
The part of displaying the numbers is no problem, the problem is when i have to sum them. I tried to use lists to save the numbers of each row and then use the first row/list and sum it but i can't get it to work.
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
}
Also in my program the mults do not show up.
Not sure what logic you are trying to undertake, but it seems a lot more difficult than
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);
try this:
int sum = IntStream.iterate(startNumber, n -> n+startNumber)
.limit(10)
.peek(System.out::println)
.sum();
Disclaimer because of downvotes. This is an alternate solution. You can look at it when you understand loops well enough I guess.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.