简体   繁体   中英

Java “For” loop output repeats

I am a beginner trying to program a java code to produce output numbers that is a prime factor of two and five.

For example, if input is 8 , then output should be 2 4 5 8 . However, whenever I print my output, the result will be 2 5 4 5 8 5.

Please advice on where I have gone wrong. Thank you

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 + " ");  
   }
  }
 }
}

After you review @AmedeeVanGasse 's comment, you need to fix your braces.

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 + " ");  
      }
   }
}

You should also review the logic in your for loop and if statements. They are full of unneeded redundancies.

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