试图打印出 100 个奇数

import java.util.*;


public class lab7 {

public static void isPrime(int n,boolean isPrime){

for (int div = 2; div < n; div++) {

        if (n % div == 0) { // n is not prime

           isPrime = false;

           div = n;

        }else{

     isPrime=true;

     }


     }   

     }


   // This program prints out the first 100 prime numbers


public static void main(String[] args) {

  int count = 0;

  int n = 1;

  boolean isPrime=true;


  // loop that iterates 100 times

  while (count <= 100) {


     // Use the isPrime method to check whether

     // the number n is prime or not

     if (isPrime(n)) {

        System.out.println(n + " is prime");

        count++;

     }


     // move on to the next n

     n++;

  }

 }

}

我试图让代码使用一种名为 isPrime 的方法打印出前 100 个奇数。我不断收到错误消息


    lab7.java:35: error: method isPrime in class lab7 cannot be applied to given types;

     if (isPrime(n)) {

         ^

required: int,boolean

found: int

我将如何摆脱它并做我想做的事。


达令说
浏览 118回答 4
4回答

皈依舞

您的isPrime(int)函数应如下所示:public static boolean isPrime(int n) {&nbsp;for (int div = 2; div < n; div++) {&nbsp; if (n % div == 0) { // n is not prime&nbsp; &nbsp;return false;&nbsp; } else {&nbsp; &nbsp;return true;&nbsp; }&nbsp;}&nbsp;return false;}您的实施不起作用,因为:你没有boolean从函数中返回Java 是按值传递的,因此您的变量isPrime不会更新还要确保不要混淆素数和奇数之间的差异。

潇潇雨雨

您的实施不起作用,因为:你没有boolean从函数中返回Java 是按值传递的,因此您的变量isPrime不会更新还要确保不要混淆素数和奇数之间的差异。

眼眸繁星

public class lab7 {public static boolean isPrime(int n,boolean isPrime){for (int div = 2; div < n; div++) {&nbsp; &nbsp; &nbsp; &nbsp; if (n % div == 0) { // n is not prime&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;isPrime = false;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;div = n;&nbsp; &nbsp; &nbsp; &nbsp; }else{&nbsp; &nbsp; &nbsp;isPrime=true;&nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp;}return isPrime;&nbsp; &nbsp; &nbsp;}&nbsp; &nbsp;// This program prints out the first 100 prime numberspublic static void main(String[] args) {&nbsp; int count = 0;&nbsp; int n = 1;&nbsp; boolean isPrime=true;&nbsp; // loop that iterates 100 times&nbsp; while (count <= 100) {&nbsp; &nbsp; &nbsp;// Use the isPrime method to check whether&nbsp; &nbsp; &nbsp;// the number n is prime or not&nbsp; &nbsp; &nbsp;if (isPrime(n, isPrime)) {&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(n + " is prime");&nbsp; &nbsp; &nbsp; &nbsp; count++;&nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp;// move on to the next n&nbsp; &nbsp; &nbsp;n++;&nbsp; }&nbsp;}}我已经更正了代码。请检查。

侃侃尔雅

我看到的问题是 isPrime 需要两个变量,在第 35 行的代码中,您只提供了 1,即整数。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java