簡體   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