我必须编写一个程序,在两个用户输入的数字之间找到素数。我遇到的唯一问题是输出有一个额外的逗号而不是它需要的。我该如何解决这个问题?
import java.util.Scanner;
public class Primes {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int start = sc.nextInt();
int end = sc.nextInt();
for (int i =start; i <= end; i++) {
if (isPrime(i)) {
System.out.printf("%d,", i);
}
}
}
public static boolean isPrime(int n) {
if (n <= 1) {
return false;
}
for (int i =2; i < Math.sqrt(n); i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
}
输入:1 10
输出:2,3,4,5,7,9,
答案 0 :(得分:4)
尝试使用StringJoiner在这种情况下更合适:
import java.util.Scanner;
public class Primes {
public static void main(String[] args) {
StringJoiner joiner = new StringJoiner(",");
Scanner sc = new Scanner(System.in);
int start = sc.nextInt();
int end = sc.nextInt();
for (int i =start; i <= end; i++) {
if (isPrime(i)) {
joiner.add(Integer.toString(i));
}
}
System.out.println(joiner.toString());
}
没有StringJoiner:
public class Primes {
public static void main(String[] args) {
String separator = "";
Scanner sc = new Scanner(System.in);
int start = sc.nextInt();
int end = sc.nextInt();
for (int i =start; i <= end; i++) {
if (isPrime(i)) {
System.out.printf(separator + "%d", i);
separator = ",";
}
}
}
答案 1 :(得分:1)
这是一种不同的方法,使用流:
String output = IntStream.rangeClosed(start, end)
.filter(Primes::isPrime)
.mapToObj(String::valueOf)
.collect(Collectors.joining(","));
System.out.println(output);