156k views
5 votes
Modify the CountByFives application so that the user enters the value to count by. Start each new line after 10 values have been displayed.

public class CountByAnything
{
// Modify the code below
public static void main (String args[])
{
final int START = 5;
final int STOP = 500;
final int NUMBER_PER_LINE = 50;
for(int i = START; i <= STOP; i += START)
{
System.out.print(i + " ");
if(i % NUMBER_PER_LINE == 0)
System.out.println();
}
}
}

User Kalabalik
by
5.5k points

1 Answer

4 votes

Answer:

The modified program is as follows:

import java.util.*;

public class CountByAnything{

public static void main (String args[]){

Scanner input = new Scanner(System.in);

final int START = 5;

final int STOP = 500;

int countBy; int count = 0;

System.out.print("Count By: ");

countBy = input.nextInt();

final int NUMBER_PER_LINE = 10;

for(int i = START; i <= STOP; i += countBy){

System.out.print(i + " ");

count++;

if(count == NUMBER_PER_LINE){

System.out.println();

count = 0;} } } }

Step-by-step explanation:

To solve this, we introduce two variables

(1) countBy --> This gets the difference between each value (instead of constant 5, as it is in the program)

(2) count --> This counts the numbers displayed on each line

The explanation is as follows:

final int START = 5;

final int STOP = 500;

This declares countBy and count. count is also initialized to 0

int countBy; int count = 0;

This prompts the user for countBy

System.out.print("Count By: ");

This gets value for countBy

countBy = input.nextInt();

final int NUMBER_PER_LINE = 10;

This iterates through START to STOP with an increment of countBy in between two consecutive values

for(int i = START; i <= STOP; i += countBy){

This prints each number

System.out.print(i + " ");

This counts the numbers on each line

count++;

If the count is 10

if(count == NUMBER_PER_LINE){

This prints a new line

System.out.println();

And then set count to 0

count = 0;}

User Santosh Hegde
by
5.6k points