簡體   English   中英

Java“ For”循環輸出重復

[英]Java “For” loop output repeats

我是一個初學者,嘗試對Java代碼進行編程以產生輸出數字,該數字是2和5的素數。

例如,如果輸入為8 ,則輸出應為2 4 5 8 但是,每當我打印輸出時,結果將是2 5 4 5 8 5。

請提供有關我哪里出問題的建議。 謝謝

import java.util.Scanner;

class twofive {
  public static void main(String [] args) {
    Scanner sc = new Scanner(System.in);
    System.out.print("Enter n:");
    int n = sc.nextInt();                                                     
    double num = 0; 
    double num2 = 0;
    for (int i = 1; (((Math.pow(2,i))<= n) || ((Math.pow(5,i)) <=n) || (((Math.pow(2,i))<= n) && ((Math.pow(5,i)) <=n))) ; i++) {
      if (( Math.pow(2,i)) <= n)                                                  
        num = (Math.pow(2,i));
      int convert = (int) num;{
        System.out.print(convert + " ");
      }
      if ((Math.pow(5,i)) <= n)
      num2 = (Math.pow(5,i));
      int convert2 = (int) num2;
      {System.out.print(convert2 + " ");  
   }
  }
 }
}

審核@AmedeeVanGasse的評論后,您需要修復花括號。

public static void main(String [] args) {
    Scanner sc = new Scanner(System.in);
    System.out.print("Enter n:");
    int n = sc.nextInt();                                                     
    double num = 0; 
    double num2 = 0;
    for (int i = 1; Math.pow(2,i))<= n) || ((Math.pow(5,i)) <=n) || (((Math.pow(2,i))<= n) && ((Math.pow(5,i)) <=n))) ; i++) {
      if (( Math.pow(2,i)) <= n) {                                                 
        num = (Math.pow(2,i));
        int convert = (int) num;
        System.out.print(convert + " ");
      }
      if ((Math.pow(5,i)) <= n) {
          num2 = (Math.pow(5,i));
          int convert2 = (int) num2;
          System.out.print(convert2 + " ");  
      }
   }
}

您還應該檢查for循環和if語句中的邏輯。 它們充滿了不必要的冗余。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM