I am trying to write a program that will list out the prime numbers up to, but not including a number determined by the user.
I want the primes to be separated by commas, but I can't seem to get rid of the comma after the final prime.
Say the user picks the number 10.
The list should be: 2,3,5,7
What I get is: 2,3,5,7,
I know this probably gets asked a lot, but I can't find anything that will help, or that I understand how to apply to my problem.
Could someone point me in the right direction?
Thanks.
Scanner scanner = new Scanner(System.in);
int i = 0;
int num = 0;
String primeNumbers = "";
System.out.println("Pick a number, any number: ");
int n = scanner.nextInt();
for (i = 1; i < n; i++) {
int counter = 0;
for (num = i; num >= 1; num--) {
if (i % num == 0) {
counter = counter + 1;
}
}
if (counter == 2) {
primeNumbers = primeNumbers + i + ",";
}
}
System.out.println("\nThe prime numbers up to " + n + " are: ");
System.out.println(primeNumbers);