繁体   English   中英

在最后一个整数前打印“and”

[英]Printing "and" before the last integer

我试图打印小于整数用户的所有素数,但在列表中的最后一个素数之前打印“和”。 有什么有效的方法可以做到这一点吗? 例如,如果用户输入 10,我希望它打印“2、3、5 和 7 都是小于 10 的素数”。

public class PrimeFinder {
    public static void main(String[] args) {

        Scanner kboard = new Scanner(System.in);
        int user = kboard.nextInt(); // sets user to users input

        for (int k = 1; k <= user; k++) {

            int numFactors = 0;

            for (int a = 1; a <= k; a++) {

                if (k % a == 0) {
                    numFactors++; //if a is divisible by k then add one to numFactors
                }
            }

            if (numFactors == 2) { // "k" is prime
                System.out.print(k + ", ");
            }
        }
        System.out.print("are all off the primes less than " + user + ".");
    }
}

您可以使用StringBuilder并在之后更新最后几个字符。 例如

// initialize size of buffer to a good estimate of what's required
StringBuilder output = new StringBuilder(k*18);
int last = 0;

for (int k=1; k<=user; k++) {
    // some other code here
    if (numFactors == 2) { // "k" is prime
        last = k;
        output.append(k).append(", ");
    }
    // some other code here
}

String lastText = Integer.toString(last);
int lastIndex = output.lastIndexOf(", " + lastText);
output.setLength(lastIndex);
output.append(" and " + lastText);

我跳过了您代码的某些部分以使其更简单。 为了完整打印Stringbuilder的内容,例如

System.out.print(output.toString() + 
    " are all off the primes less than " + user + ".");

您可以使用 ArrayList 并存储它们。 在找到所有质数后,您可以轻松分辨出该范围内的最后一个。

import java.util.ArrayList;
import java.util.Scanner;

public class PrimeFinder {
    public static void main(String[] args) {

        Scanner kboard = new Scanner(System.in);
        int user = kboard.nextInt(); // sets user to users input
        //Iltis: create array list
        ArrayList<Integer> prime = new ArrayList<Integer>();

        for (int k = 1; k <= user; k++) {

            int numFactors = 0;

            for (int a = 1; a <= k; a++) {

                if (k % a == 0)
                    numFactors++; // if a is divisible by k then add one to
                                    // numFactors

            }
            if (numFactors == 2) { // "k" is prime
                //Iltis: add all primes
                prime.add(k);
            }

        }
        for (int i = 0; i < prime.size()-2; i++) {
            //Iltis: printing all primes except the last two
            System.out.print(prime.get(i)+", ");
        }
        //Iltis: print the last two
        System.out.print(prime.get(prime.size()-2)+" and "+prime.get(prime.size()-1));
        System.out.print(" are all off the primes less than " + user + ".");
    }
}

跟踪变量中的前一个素数(例如previous )。 最初,将其设置为 -1。 (您可能还想使用额外的布尔变量来跟踪是否需要在打印数字之前打印逗号)。

如果找到素数,则打印前一个素数(如果不是 -1),并将当前素数存储在previous

最后,打印" and " + previous

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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