亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

試圖打印出 100 個奇數

試圖打印出 100 個奇數

達令說 2022-07-14 10:17:46
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 numberspublic 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,booleanfound: int我將如何擺脫它并做我想做的事。
查看完整描述

4 回答

?
皈依舞

TA貢獻1851條經驗 獲得超3個贊

您的isPrime(int)函數應如下所示:


public static boolean isPrime(int n) {

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

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

   return false;

  } else {

   return true;

  }

 }


 return false;

}

您的實施不起作用,因為:

  1. 你沒有boolean從函數中返回

  2. Java 是按值傳遞的,因此您的變量isPrime不會更新

還要確保不要混淆素數和奇數之間的差異。


查看完整回答
反對 回復 2022-07-14
?
瀟瀟雨雨

TA貢獻1833條經驗 獲得超4個贊

您的實施不起作用,因為:


你沒有boolean從函數中返回

Java 是按值傳遞的,因此您的變量isPrime不會更新

還要確保不要混淆素數和奇數之間的差異。


查看完整回答
反對 回復 2022-07-14
?
眼眸繁星

TA貢獻1873條經驗 獲得超9個贊

public class lab7 {

public static boolean 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;

     }


     }

return isPrime;

     }


   // 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, isPrime)) {

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

        count++;

     }


     // move on to the next n

     n++;

  }

 }

}

我已經更正了代碼。請檢查。


查看完整回答
反對 回復 2022-07-14
?
侃侃爾雅

TA貢獻1801條經驗 獲得超16個贊

我看到的問題是 isPrime 需要兩個變量,在第 35 行的代碼中,您只提供了 1,即整數。



查看完整回答
反對 回復 2022-07-14
  • 4 回答
  • 0 關注
  • 136 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號