2016-12-04 97 views
-5

我应该用java编写一个程序,它允许用户确定他想要显示的素数的数量(数量)。 我已经设法编写了一个程序,用户可以在其中指定最大素数。 我可以请你提一些建议吗?素数与键盘输入

import java.util.Scanner; 

public class PrimeNumbers{ 
    public static void main(String[] agrs){ 

    int max; 

    Scanner sk = new Scanner(System.in); 
    System.out.print("How many prime numbers you want to display? "); 
    max = sk.nextInt(); 

    System.out.print("Prime numbers: "); 

    for(int x =2; x <= max; x++){ 
     boolean isPrime = true; 
     for(int y = 2; y < x; y++){ 
      if(x % y == 0){  
       isPrime = false; 
       break; 
     } 
     }if (isPrime){ 
      System.out.print(x + " "); 
    } 

} System.out.print("..."); 
} 
} 

如果即把我作为一个用户5,我得到的只有2,3,5 但我希望得到的结果是:2,3,5,7,11

+0

我想你的意思是用户指定要打印的素数,这是我如何回答它。 –

+2

欢迎来到Stack Overflow!看起来你正在寻求作业帮助。虽然我们本身没有任何问题,但请观察这些[应做和不应该](http://meta.stackoverflow.com/questions/334822/how-do-i-ask-and-answer-homework-questions/338845#338845),并相应地编辑您的问题。 –

回答

0

曲目的数量你打印的素数,不是x。检查您是否打印足够。

import java.util.Scanner; 

public class PrimeNumbers{ public static void main(String[] agrs){ 

int max; 
int numPrinted=0; 
Scanner sk = new Scanner(System.in); 
System.out.print("How many prime numbers you want to display? "); 
max = sk.nextInt(); 

System.out.print("Prime numbers: "); 

for(int x =2; numPrinted < max; x++){ 
    boolean isPrime = true; 
    for(int y = 2; y < x; y++){ 
     if(x % y == 0){  
      isPrime = false; 
      break; 
    } 
    }if (isPrime){ 
     System.out.print(x + " "); 
     numPrinted++; 
} 

} System.out.print("..."); 

} } 
+0

非常感谢你! :) – KejP

+0

@KejP。 Ubetcha。我怀疑你说的话是你的意思。另外,如果你喜欢答案,请接受它。 –