Java/PHP/GitLab Fan, Passionate Developer and Loves Teaching

0%

Prime Numbers Between Range Java

Summary

Java code using Swing GUI to find prime number between a range using two types of methods

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package primeswing;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;

/**
*
* @author Rohan
*/
public class PrimeSwing extends JFrame implements ActionListener {

int range_number;
JPanel number, buttons;
JTextField txtNumber;
JButton method1, method2;
JLabel lblNumber;
JFrame output;
JLabel lblOutput;

public PrimeSwing() {
range_number = 0;
output = new JFrame("Output of Prime");
txtNumber = new JTextField(10);
lblOutput = new JLabel();
number = new JPanel();
method1 = new JButton("Method 1");
method2 = new JButton("Method 2");
lblNumber = new JLabel("Enter number: ");
buttons = new JPanel();
method1.addActionListener(this);
method2.addActionListener(this);
number.add(lblNumber);
number.add(txtNumber);
add(number);
buttons.add(method1);
buttons.add(method2);
add(buttons, BorderLayout.SOUTH);
setSize(300, 100);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Find Prime Number");
}

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
new PrimeSwing();
}

// Method 2 using static method
static boolean isPrime(int number) {
boolean isPrime = false;
int i = (int) Math.ceil(Math.sqrt(number));
while (i > 1) {
if ((number != i) && (number % i == 0)) {
isPrime = false;
break;
} else if (!isPrime) {
isPrime = true;
}
--i;
}
return isPrime;
}

@Override
public void actionPerformed(ActionEvent e) {

if (!txtNumber.getText().equals("")) {
range_number = Integer.parseInt(txtNumber.getText());
output.setSize(350, 600);
output.setVisible(true);
String temp = "<html>";
boolean prime;
if (e.getSource() == method1) {
temp += "Using Method 1<br />";
temp += "<ul>";
for (int i = 2; i < range_number; i++) {
prime = true;
for (int j = 2; j < i; j++) {
if (i % j == 0 && i != j) {
prime = false;
break;
}
}
if (prime) {
temp = temp + "<li>" + i + "</li>";
}
}
temp += "</ul>";
}
else if(e.getSource() == method2)
{
temp += "Using Method 2<br />";
temp += "<ul>";
for (int i = 1; i < range_number; i++) {
if(PrimeSwing.isPrime(i))
{
temp = temp + "<li>" + i + "</li>";
}
}
temp += "</ul>";
}
temp = temp + "</html>";
lblOutput.setText(temp);
output.add(lblOutput);
} else {
JOptionPane.showMessageDialog(this, "Please enter some number");
}
}
}