473,323 Members | 1,589 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,323 software developers and data experts.

How do I write a method named isPrime, which takes an integer as an argument and

A prime number is a number that is only evenly divisible by itself and 1. For example, the number 5 is prime because it can only be evenly divided by 1 and 5. The number 6, however, is not prime because it can be divided evenly by 1, 2, 3, and 6.
Write a method named isPrime, which takes an integer as an argument and returns true if the argument is a prime number, or false otherwise. Demonstrate the method in a complete program.

This is what I have so far.

import javax.swing.JOptionPane;

public class PrimeChecker
{

public static void main(String[] args)
{
String input; // To hold keyboard input
String message; // Message to display
int number; // Number to check for prime

// Get the number.
input = JOptionPane.showInputDialog("Enter a number.");
number = Integer.parseInt(input);

// Determine whether it is prime or not.
if (isPrime(number))
message = "That is a prime number.";
else
message = "That is not a prime number.";

// Display a message.
JOptionPane.showMessageDialog(null, message);

System.exit(0);
}

}
Mar 26 '10 #1
5 9960
jkmyoung
2,057 Expert 2GB
Alright, where is the code for your isPrime function? What algorithm do you intend to use?
Mar 26 '10 #2
I want to use the % operator, but I don't know how to use it. I also want to use the code String num = but I don't know what to put after it. I went and added so stuff but I don't know if it is correct. This is what I have now.

import javax.swing.JOptionPane;

public class PrimeChecker
{
String num =

if (number % number == 0 || number % number == 1)
status = true;
else
status = false;



public static void main(String[] args)
{
String input; // To hold keyboard input
String message; // Message to display
int number; // Number to check for prime

// Get the number.
input = JOptionPane.showInputDialog("Enter a number.");
number = Integer.parseInt(input);

// Determine whether it is prime or not.
if (isPrime(number))
message = "That is a prime number.";
else
message = "That is not a prime number.";

// Display a message.
JOptionPane.showMessageDialog(null, message);

System.exit(0);
}

}
Mar 27 '10 #3
pbrockway2
151 Expert 100+
I want to use the % operator, but I don't know how to use it. I also want to use the code String num = but I don't know what to put after it.
The remainder operator (%) is used like any other binary arithmetic operator: you put it in between two values to obtain a third.

Expand|Select|Wrap|Line Numbers
  1. int result = 6 * 7;
  2. System.out.println(result); // prints 42
  3. result = 5 % 2;
  4. System.out.println(result); // prints 1
  5.  
As for initialising a string variable, you can use a string literal (something in "quotes") or any expression that yields a string:

Expand|Select|Wrap|Line Numbers
  1. String num = "Hello world";
  2. System.out.println(num); // prints Hello world
  3. num = String.valueOf(6 * 7);
  4. System.out.println(num); // prints 42
  5.  
If you'll pardon me, your statement of what you want seems a bit aimless. What I mean is: how do you intend using the % operator (for what purpose?), why do you want a String variable num?

I went and added so stuff but I don't know if it is correct.
I would suggest not writing code whose correctness is unknown. Throwing stuff at a wall in the hope that some of it might stick is futile and quickly becomes frustrating.

Instead:

(1) Figure out an algorithm (a plain English description of the steps to be followed) that will implement the isPrime() method you used in your original post. If you are unsure about the correctness of that algorithm then state it and you will have provided a precise and purposeful question.

(2) Consult your textbook/teacher/classmates etc and decide on the overall program structure - what methods the class will have, their argument and return types and their purpose. At this point the compiler will detect any mistakes of Java syntax and, if you can't understand them, you will again have things to post and precise questions to ask. Ie, post the code and the exact and entire compiler message. I would add that it is a good idea to compile early and often so that the syntax errors can be corrected one at a time as they occur.

(3) Once you have running code, test it. If the runtime behaviour is not what you intend then, once again, you have something to post (the code and a description of the behaviour) and a precise question to ask. (why did this occur?).

Good luck!
Mar 27 '10 #4
jkmyoung
2,057 Expert 2GB
if BigNumber % divisor == 0, then when you divide the BigNumber by divisor you get no remainder. That is, the divisor divides BigNumber evenly.

-> If the divisor is smaller than the number, then BigNumber is not prime.

?Do you know how to use functions? (eg like you have with isPrime(number))
Mar 29 '10 #5
anmoldhima5
2 2Bits
A number is prime number if it is only divided by 1 or itself . So we iterate loop 2 to Math.sqrt(number ) and check it
Below i have shared code for this
Expand|Select|Wrap|Line Numbers
  1. public class HelloWorld{
  2.  
  3.      public static void main(String[] args) {
  4.       int n =7;
  5.       if(isPrimeNumber(n)){
  6.             System.out.println("number "+ n +" is prime");
  7.            }else{
  8.            System.out.println("number "+ n +" is not prime");
  9.         }
  10.      }
  11.  
  12.      public static boolean isPrimeNumber(int n) {
  13.          int j = (int) Math.sqrt(n);
  14.          for(int i=2 ; i <= j ; i++){
  15.          if(n%i==0)
  16.          {
  17.              return false;
  18.          }
  19.          }
  20.         return true;
  21.      }
  22.  
  23. }
Source : Check number is prime or not
Jan 20 '21 #6

Sign in to post your reply or Sign up for a free account.

Similar topics

31
by: Chris S. | last post by:
Is there a purpose for using trailing and leading double underscores for built-in method names? My impression was that underscores are supposed to imply some sort of pseudo-privatization, but would...
4
by: daniel.w.gelder | last post by:
I wrote a template class that takes a function prototype and lets you store and call a C-level function, like this: inline string SampleFunction(int, bool) {..} functor<string (int, bool)>...
13
by: Stumped and Confused | last post by:
Hello, I really, really, need some help here - I've spent hours trying to find a solution. In a nutshell, I'm trying to have a user input a value in form's textfield. The value should then be...
3
by: Manfred Braun | last post by:
Hi All, I am able to invoke some methods from an instance of a loaded assembly, but I am not able to invoke the loaded assemblie's "Main" method. I try it this way: Assembly assembly =...
4
by: Gianluca | last post by:
This is the simplified code I'm trying to generate: ilg.DeclareLocal(typeof(int)); // define local integer Label exit = ilg.DefineLabel(); // define "exit" label ...
44
by: gregory.petrosyan | last post by:
Hello everybody! I have little problem: class A: def __init__(self, n): self.data = n def f(self, x = ????) print x All I want is to make self.data the default argument for self.f(). (I
5
by: Martin P. Hellwig | last post by:
While I was reading PEP 8 I came across this part: """ Function and method arguments Always use 'self' for the first argument to instance methods. Always use 'cls' for the first argument to...
1
by: ladislav | last post by:
I need modify first program.In second program I try print method findPrime in method main.I have there anywhere mistakes.Please obout help. First program: ** *PrimeNumber.java * *
1
by: EquinoX | last post by:
I am writing a method with header like this: public Set<E> union (Set<E> other){ } say I have a test method: @Test public void testUnion() {
8
by: defn noob | last post by:
isPrime works when just calling a nbr but not when iterating on a list, why? adding x=1 makes it work though but why do I have to add it? Is there a cleaner way to do it? def isPrime(nbr):...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.