简体   繁体   中英

How to make a new Line every 8th input

My code requires me to create an array (from user input), display it backwards, and find the sum of each number. So far I have been able to accomplish all requirements. However, if the array is more than 8 numbers, then when it is displayed the program must create a new line every 8th number. I'm having difficulty accomplishing this goal. Here is my code so far:

import java.util.Scanner;

public class arrayCreator {

    public static void main(String[] args) {

        int length;
        double sumArray = 0;

        Scanner input = new Scanner(System.in);
        System.out.print("How many elements in the array? ");
        length = input.nextInt();

        }

        for(int j = currentArray.length-1; j >= 0; j-- )
        {
            System.out.printf("%.3f \t", currentArray[j]);

            if(currentArray.length - 8 == j) // here is where I'm having the problem
            {
                System.out.print("\n");
            }


        input.close();
    }

}

What should go inside of the if statement in order to create a new line each time 8 inputs are displayed?

This is what output should look like:

How many elements in the array? 20

Please enter the next value 1

Please enter the next value 2

Please enter the next value 3

Please enter the next value 4

Please enter the next value 5

Please enter the next value 6

Please enter the next value 7

Please enter the next value 8

Please enter the next value 9

Please enter the next value 10

Please enter the next value 11

Please enter the next value 12

Please enter the next value 13

Please enter the next value 14

Please enter the next value 15

Please enter the next value 16

Please enter the next value 17

Please enter the next value 18

Please enter the next value 19

Please enter the next value 20

20.000 19.000 18.000 17.000 16.000 15.000 14.000 13.000
12.000 11.000 10.000 9.000 8.000 7.000 6.000 5.000
4.000 3.000 2.000 1.000

The Sum of the array's elements is: 210.000

The other answer isn't working correctly because you're backing up through the list from the end back to the beginning, but the mod operator causes line breaks as if you were moving from the beginning to the end. However, the idea of using the modulo operator is definitely correct. Do this in your if statement:

if((length - j) % 8 == 0) {
    System.out.print("\n");
}

Usually when you want to do something every n times, you want to use modulo division : % .

Change this

if(currentArray.length - 8 == j) // here is where I'm having the problem
{
    System.out.print("\n");
}

To this

if (j % 8 == 0) // here is where I'm having the problem
{
    System.out.print("\n");
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM