简体   繁体   中英

My code will compile but when I run it, it has an error. Why?

The code shows:

java.util.IllegalFormatConversionException: d != java.lang.String at java.util.Formatter$FormatSpecifier.failConversion(Formatter.java:4302) at java.util.Formatter$FormatSpecifier.printInteger(Formatter.java:2793) at java.util.Formatter$FormatSpecifier.print(Formatter.java:2747) a

public class addiePorterMod10Sieve {
    void sieveOfEratosthenes(int n) {
        boolean prime[] = new boolean[n + 1];
        for (int i = 0; i < n; i++)
            prime[i] = true;
        for (int p = 2; p * p <= n; p++) {
            if (prime[p] == true) {
                for (int i = p * p; i <= n; i += p)
                    prime[i] = false;
            }
        }
        for (int i = 2; i <= n; i++) {
            if (prime[i] == true)
                System.out.printf(i + "%-1s %-15n", " ");
        }
    }

    public static void main(String args[]) {
        int n = 1000;
        addiePorterMod10Sieve g = new addiePorterMod10Sieve();
        g.sieveOfEratosthenes(n);
    }
}

Not very familiar with formatter myself, but the below workaround should achieve what you need as ouput :

int linecount = 0;
for(int i = 2; i <= n; i++) 
{          
     if(prime[i] == true)  {
      //   System.out.printf(i + "%-1s %-15d", " "); 
           linecount++;                   
           System.out.print(i + " ");
           if (linecount == 15) { 
              linecount =0;
              System.out.println();
           }
      }
}

The error derives from %'s matching with a parameter.

    int p = 0;
    String nl = "\r\n";
    for (int i = 2; i <= n; i++) {
        if (prime[i]) {
            ++p;
            System.out.printf("%-15d ", i);
            if (p % 10 == 0) {
                System.out.println();
            }
            //System.out.printf("%-15d%s", i, (p % 10 == 0 ? nl : " "));
        }
    }

Now %n would indeed yield a newline ( "\\r\\n" on Windows, "\\n" on Linux) with a flush of the line. However you must place it in the format string,

My out-commented alternative misses immediate flushing to the console.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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