Reputation: 33
I am trying to get a Java program to print a specific amount of spaces per line and then drop down to continue the list. I am finding all prime numbers in a user specified range and then printing out the number of primes in the range and the prime numbers themselves. Anytime the program finds a number that is not a prime number it should print a - . So far, I have:
import java.util.Scanner;
public class PrimeNums {
public static void main(String[] args) {
Scanner keyboard= new Scanner(System.in);
int startingVal;
int endingVal;
int index;
int currNum = 2;
boolean prime;
int count=0;
//*** Input ***
System.out.println("Enter the Starting Number of the Range: ");
startingVal = keyboard.nextInt();
System.out.println("Enter the Ending Value of the Range: ");
endingVal = keyboard.nextInt();
//*** Checks for Parameters ***
while(startingVal>1000||startingVal%10!=0){
System.out.println("Starting Value was not evenly divisible by 10. Reenter Starting Value: ");
startingVal= keyboard.nextInt();
}
while(startingVal>=endingVal||endingVal%10!=0||endingVal>1000){
System.out.println("Ending Value was less than Starting Value or Did Not Follow Guideline. Reenter Ending Value: ");
endingVal=keyboard.nextInt();
}
//*** Stores Checked Variables ***
int range = (endingVal);
int[] primeArray = new int[10];
//*** Checks for all Prime Numbers ***
for(index=startingVal; index<range; index++){
if(index==1||index%2==0||index%3==0||index%4==0||index%5==0||index%6==0||index%7==0||index%8==0||index%9==0||index%10==0){
System.out.print("-");
}else{
count++;
System.out.print(index);
}
}
System.out.println("There are " + count + " Prime Numbers in this range.");
}
}
So far, this program finds all the prime numbers within the range and prints them out. However, I need the code to print out in sets of 10. Something like this: Range here is: 70-200.
71 - 73 - - - - - 79 - | 80
101 - 103 - - - 107 - 109 - | 110
131 - - - - - 137 - 139 - | 140
181 - - - - - - - - - | 190
191 - 193 - - - 197 - 199 - | 200
There are 27 prime numbers between 70 and 200
Upvotes: 0
Views: 3383
Reputation: 7076
By subtracting the starting value with index you'll get the loop number, which will be the same as if you were using a counter. Once you know that, %sizeOfSet == 0
will return true if the counter is divisible by sizeOfSet
(the number of outputs per set, as you specified, 10).
int sizeOfSet = 10;
if ((index-startingVal) %sizeOfSet == 0){
//prints out an empty line
System.out.printf("%n");
}
This code should be included at the end of the for loop after the if-else statement.
Upvotes: 1