for loop finding the prime numbers

后端 未结 5 2093
生来不讨喜
生来不讨喜 2020-12-20 03:05

I am trying to run this code to print the sum of all the prime numbers less than 2 million. This loop is never ending. Can anyone tell me what is wrong with the code? It see

5条回答
  •  悲哀的现实
    2020-12-20 03:40

    Here is a complete program of Prime using JOptionPane, i.e. Java GUI

    import javax.swing.*;
    
    public class ChkPrime {
        public static void main(String[] args) throws NumberFormatException {
            String str = JOptionPane.showInputDialog(null, "Enter any number: ","Input...", 3);
    
            try {
                int num = Integer.parseInt(str);
    
    
                if (num == 1)
                    JOptionPane.showMessageDialog(null, "Your inputed no. " + num + " is not prime.","Error!", 0);
    
                for(int i = 2; i <= Math.sqrt(num); i++) {
                    if(num % i == 0) {
                        JOptionPane.showMessageDialog(null, "Your inputed no. " + num + " is not prime.","Error!", 0);
                        System.exit(0);
                    }
                }
    
                JOptionPane.showMessageDialog(null, "Your inputed no. " + num + " is prime.","Yeh! Got it!", 1);
            }
    
            catch (NumberFormatException e) {
                JOptionPane.showMessageDialog(null, "Please input numbers...","Error!", 0);
                main(null);
            }
        }
    }
    

提交回复
热议问题