OK, I know I am missing something easy here, however I cannot find my mistake. The program runs fine, it just returns the wrong message. I am not calling it properly or something. I can remove the code form the display() method and put it in the check() method and it runs perfectly. Anyone want to help out a newbie who is stuck? I was unsure if the whole program needed to be displayed, if not I am sorry. A few times before I was told I did not put enough code in. I would also like any constructive feedback on the way I have written the code, as I do not want to pick up any bad habits.
public class Palindrome {
// Main Method
public static void main(String[] args) {
// Declare variables
int number;
// Call method
number = retrieveInput();
check(number);
display();
}// End main method
//*************************************************************************************
// Method to retrieve the input
public static int retrieveInput(){
//Declare variables
String number = null;
int numInput = 0;
boolean done = false;
// Prompt user for input and validate that input
while(!done){
try{
number = JOptionPane.showInputDialog("Enter 5 single digits");
numInput = Integer.parseInt(number);
if (numInput <10000 || numInput > 99999)
throw new NumberFormatException();
else
done = true;
}
catch(NumberFormatException e)
{
JOptionPane.showMessageDialog(null, "Entry invalid. Please re-enter 5 single digits", "Error", JOptionPane.ERROR_MESSAGE);
}
}
return numInput;
}// End retrieveInput method
//*************************************************************************************
// Method to determine if input is a palindrome or not
public static boolean check(int number){
//Declare variables
int num1;
int num2;
int num4;
int num5;
boolean isPalindrome = false;
num1 = number / 10000;
num2 = number % 10000 / 1000;
num4 = number % 100/10;
num5 = number % 10;
// Checking to see if input is a palindrome
if (num1 == num5 && num2 == num4);
{
isPalindrome = true;
}
if (num1 != num5 && num2 != num4);
{
isPalindrome = false;
}
return isPalindrome;
}// End check method
//*************************************************************************************
// Method to display results
public static void display(){
// Declare variable
boolean isPalindrome = false;
// Display results
if (isPalindrome == true)
{
JOptionPane.showMessageDialog(null, "These 5 digits are a palindrome", "Results", JOptionPane.INFORMATION_MESSAGE);
}
else
{
JOptionPane.showMessageDialog(null, "These 5 digits are NOT a palindrome", "Results", JOptionPane.INFORMATION_MESSAGE);
}
} // End display method
//*************************************************************************************
} // End class Palindrome
Change the last two lines of main to read
boolean isPalindrome = check(number);
display(isPalindrome);
Change the declaration of display to
public static void display(boolean isPalindrome){
and remove the line in display that says
boolean isPalindrome = false;
That way, the isPalindrome that display works with will be the same one that was evaluated in check.
Edit:
Also remove the semicolon at the end of
if (num1 != num5 && num2 != num4);
otherwise the block underneath it will run in every case, and set isPalindrome back to false. Alternatively, you could just remove this condition and the block below it entirely, because it actually doesn't do anything.
isPalindrome should be in your main method and take the value from your check method. Then pass it to display method. The way it is now the isPalindrome is always false, because it is just initialized to false in your display method and never changes.
Oh my god, you did something very silly in the check method. You say that isPalindrome is false, then display the value of isPalindrome without taking into account the fact that isPalindrome is calculated by a very different method and you have no way to get the value of it. What you can do is the same approach you used to get the number out of retrieveInput and put in check: function arguments. Here's a revised display method:
public static void display(boolean isPalindrome){
// Declare variable
boolean isPalindrome = false;
// Display results
if (isPalindrome == true)
{
JOptionPane.showMessageDialog(null, "These 5 digits are a palindrome", "Results", JOptionPane.INFORMATION_MESSAGE);
}
else
{
JOptionPane.showMessageDialog(null, "These 5 digits are NOT a palindrome", "Results", JOptionPane.INFORMATION_MESSAGE);
}
}
Then, the main method needs to look like this:
public static void main(String[] args) {
// Declare variables
int number;
boolean isPalindrome
// Call method
number = retrieveInput();
isPalindrome = check(number);
display(isPalindrome);
}
the problem lies in that you aren't doing anything with the value you get back from check(). After you call it in main(), the value disappears since you don't assign it to any thing. Then in display() you create a new instance of isPalindrome and set it to false. this one has nothing to do with the one declared in check(). this one will always be false because you don't tell it otherwise. to fix it change your main() method's body to:
// Declare variables
int number;
boolean isPalindrome; //declare var
// Call method
number = retrieveInput();
isPalindrome = check(number); //assign it the value
display(isPalindrome); //pass this value on to display
and then your display to
public static void display(boolean isPalindrome){
// Declare variable
//don't need to decalre var as
//it is now a parameter to the function
//rest of method as before
}
This will allow your display to know whether or not the number is a palindrome or not.
Edit Also you are doing if's wrong!
after an if statement there is no semicolon!!
as a a result your' if's in check do absolutely nothing and will always return false!
also keep in mind what would happen with the number 12325. it is not a palindrome but it's first and last digits are the same whereas the second and forth are. neither of your if statements would evaluate as true if they were correct. the following is the fixed code:
import javax.swing.JOptionPane;
public class Palindrome {
// Main Method
public static void main(String[] args) {
// Declare variables
int number;
boolean isPalindrome; //add this var to store the value
// Call method
number = retrieveInput();
isPalindrome = check(number); //assign it so we know wheter it a palindrome or not
display(isPalindrome); //pass it to display() so it mknows wheter it is a palindrome or not
}// End main method
//*************************************************************************************
// Method to retrieve the input
public static int retrieveInput() {
//Declare variables
String number;
int numInput = 0;
boolean done = false;
// Prompt user for input and validate that input
while (!done) {
try {
number = JOptionPane.showInputDialog("Enter 5 single digits");
numInput = Integer.parseInt(number);
if (numInput < 10000 || numInput > 99999) { //don't throw an error, inefecient just show the error instead
JOptionPane.showMessageDialog(null, "Entry invalid. Please re-enter 5 single digits", "Error", JOptionPane.ERROR_MESSAGE);
} else {
done = true;
}
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null, "Entry invalid. Please re-enter 5 single digits", "Error", JOptionPane.ERROR_MESSAGE);
}
}
return numInput;
}// End retrieveInput method
//*************************************************************************************
// Method to determine if input is a palindrome or not
public static boolean check(int number) {
//Declare variables
int num1,num2,num4,num5;
boolean isPalindrome;
num1 = number / 10000;
num2 = number % 10000 / 1000;
num4 = number % 100 / 10;
num5 = number % 10;
// Checking to see if input is a palindrome
if (num1 == num5 && num2 == num4){ //no semicolons!!! else the if does nothing
isPalindrome = true; // and it evaluateds whaat it was supposed to like normal code
}else{
isPalindrome = false;
}
return isPalindrome;
}// End check method
//*************************************************************************************
// Method to display results
public static void display(boolean isPalindrome) { // no variables to declare as it now a parameter
// Display results
if (isPalindrome == true) {
JOptionPane.showMessageDialog(null, "These 5 digits are a palindrome", "Results", JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(null, "These 5 digits are NOT a palindrome", "Results", JOptionPane.INFORMATION_MESSAGE);
}
} // End display method
//*************************************************************************************
} // End class Palindrome
Related
I'm working on an assignment and I mostly have it finished but I am having an issue with the last method. I'm trying to write a continueGame() method that will ask the user if they want to continue to play, and accept "y" or "n". If answered "y", the program starts again. If answered "n", the program stops and a message is shown. The problem is I need it to trigger the continueGame() method only when userChoice == answer. This is a number guessing game with an object oriented approach.
I've tried to call the continueGame() method inside my else if(userChoice == answer) statement but it doesn't seem to work. Even when my other if/else if statements are triggered, it continues to the continueGame() method.
Here is the main driver for the game
import java.util.Scanner;
public class NumberGame
{
public static void main(String[] args)
{
Scanner input = new Scanner (System.in);
GameOptions opt = new GameOptions(); // Your created class
int userChoice = -1234;
int answer = -1234;
boolean keepPlaying = true;
System.out.println("Guess the Number Game\n");
while (keepPlaying == true) {
answer = (int) (Math.random() * 10)+1;
//Create a getChoice method in your class and make sure it accepts a Scanner argument
userChoice = opt.getChoice(input);
//Create a checkAnswer method in your class. Make sure it accepts two integer arguments and a Scanner argument
opt.checkAnswer(userChoice, answer, input);
// Create a continueGame method in your class and make sure it accepts a Scanner argument
keepPlaying = opt.continueGame(input);
}
System.out.println("Thanks for playing.");
}
}
Here is the class that I am working on for the methods. Note that I can not make any modifications to the main driver file.
import java.util.InputMismatchException;
import java.util.Scanner;
import java.lang.NumberFormatException;
public class GameOptions {
int count = 0;
boolean cont = true;
//getChoice Method for NumberGame
public int getChoice(Scanner scnr) {
System.out.println("Please choose a number between 1 and 10: ");
int userGuess = 0;
String input = scnr.next();
try {
userGuess = Integer.parseInt(input);
if (userGuess < 1 || userGuess > 10) {
throw new IllegalArgumentException("Invalid value. Please enter a number between 1 and 10: ");
}
}
catch(NumberFormatException e) {
System.out.println("Error - Enter Numerical Values Only");
return userGuess;
}
catch (IllegalArgumentException ex) {
System.out.println(ex.getMessage());
}
return Integer.parseInt(input);
}
public void checkAnswer(int userChoice, int answer, Scanner scnr) {
if (userChoice > answer && userChoice < 11) {
System.out.println("Too high. Try again.");
count++;
} else if (userChoice < answer && userChoice > 0) {
System.out.println("Too low. Try again.");
count++;
} else if (userChoice == answer) {
System.out.println("You got it! Number of tries: " + count);
System.out.println("Would you like to play again? (y/n)");
}
}
public static boolean continueGame(Scanner scnr) {
String input = scnr.nextLine();
if (input.toLowerCase().equals("y")){
return true;
} else if (input.toLowerCase().equals("n")){
return false;
} else {
System.out.println("Invalid entry. Please enter either y or n: ");
return continueGame(scnr);
}
}
}
So I should be able to enter a number, and if its lower than the answer it will tell me I am too low, if its higher than the answer it will tell me that its too high, if its equal it will tell me I won and prompt me to press "y" or "n" if I want to continue. Another issue I am running into is that I am getting "Would you like to play again? (y/n)" no matter whether I guess the right number or not and my only option is to hit "y" or "n"
The driver class is calling continueGame() inside the while loop. If you're not allowed to modify that class then presumably asking at every iteration is the intended behaviour.
You should move System.out.println("Would you like to play again? (y/n)"); into the continueGame() method so that it only asks when that method is called.
The way the driver is written (I guess) is coming from your instructor/lecturer/professor, right?
With the driver (as it is), you don't need to call continueGame method from checkAnswer method. The driver is going to call it.
Just run the driver and it will work. If you have a proper IDE (eclipse or Netbeans), trace through and see what the input accepted is (I think there is line-feed in the accepted answer).
Try this (I just changed the loop structure; yours is also valid):
public static boolean continueGame(Scanner scnr) {
while (true) {
String input = scnr.nextLine().trim(); // to remove white spaces and line-feed
if (input.toLowerCase().equals("y")){
return true;
} else if (input.toLowerCase().equals("n")){
return false;
} else {
System.out.println("Invalid entry. Please enter either y or n: ");
}
}
}
Added for checkAnswer method to keep the user guess the answer until he gets correct:
public static checkAnswer(/*three arguments*/) {
boolean correct = false;
while (! correct) {
// accept input
if (answer.equals(input)) {
correct = true;
// print required correct/congrats messages here
} else {
// print required input/try again messages here
}
}
// print would you like to play again with new answer y/n message here.
}
In my opinion, printing "play again with new answer y/n message" should go into continueGame method (from last portion of checkAnswer) method to stick to encapsulation concepts.
This question already has answers here:
Cant figure out how to exit the loop of my program
(3 answers)
Closed 6 years ago.
My program for class asks to run the program as long as the user doesn't enter the input of -99. When I run the program and enter a usable number that isn't -99, the console will run a continuous looping answer until I have to press end.
How can I change the program so for each input there will be one answer and the program restarts until user inputs -99?
import java.util.Scanner; //import scanner
import java.io.*; //import library
public class is_odd_or_even_number {//begin class
public static void main(String []args) {//begin main
Scanner input = new Scanner(System.in);
//use try/catch method to test for invalid input
try{
//promt user to input a value
System.out.print("Enter a positive integer value: ");
int number = input.nextInt();
//PART I NEED HELP WITH **************
while (number != -99){
//Start of if statement to test which to print and call of isEven method
if (isEven(number)) {
System.out.println("Your number is Even!");
}
else
System.out.println("Your number is Odd!");
}
}
//open catch method and print invalid
catch(Exception notNumber) {
System.out.println("Input not a number, try again.");
}
}
//begin testing for odd or even in new method
public static boolean isEven(int num){
return(num & 1) == 0;
}
}
Here, you don't let the user entry other thing that the first input before the loop.
The retrieval of the input from the user :
int number = input.nextInt();
should be in the loop.
Try that :
int number = 0;
//PART I NEED HELP WITH **************
while (number != -99){
number = input.nextInt();
//Start of if statement to test which to print and call of isEven method
if (isEven(number)) {
System.out.println("Your number is Even!");
}
else
System.out.println("Your number is Odd!");
}
}
You can do like this way ;)
System.out.print("Enter a positive integer value: ");
int number = input.nextInt();
//PART I NEED HELP WITH **************
while (number != -99){
System.out.print("Not good, please enter a new one : ");
number = input.nextInt();
}
//Start of if statement to test which to print and call of isEven method
if (isEven(number)) {
System.out.println("Your number is Even!");
}
else {
System.out.println("Your number is Odd!");
}
So it will ask until you're not writing -99 as you said, but if you're asking for "a positive int" normally nobofy would write -99 :p
End a while loop
You can use a boolean value shouldContinue to control whether the programs should continue to the next input.
if (number != -99) {
shouldContinue = true;
} else {
shouldContinue = false;
}
This can be simplified as follow:
shouldContinue = number != -99 ? true : false;
// or even shorter
shouldContinue = number != -99;
Read the value correctly
But you need to ensure that you input number is reset at each loop execution so that you can read the next number:
while (shouldContinue) {
...
number = input.nextInt();
}
Other enhancements
Do not import unused packages or classes
Use camel case for Java class name
Use comment style /** ... */ for Javadoc
Always try to avoid infinite loop, e.g. use an integer count tries and count down at each loop.
Here's the final answer look like:
import java.util.Scanner;
public class IsOddOrEvenNumber {
public static void main(String []args) {
Scanner input = new Scanner(System.in);
boolean shouldContinue = true;
int tries = 0;
while (shouldContinue && tries < 10) {
try {
System.out.print("Enter a positive integer value: ");
int number = input.nextInt();
if (isEven(number)) {
System.out.println("Your number is Even!");
} else {
System.out.println("Your number is Odd!");
}
shouldContinue = number != -99 ? true : false;
} catch (Exception notNumber) {
System.out.println("Input not a number, try again.");
}
tries--;
}
System.out.println("Game over.");
}
/**
* Begin testing for odd or even in new method
*/
public static boolean isEven(int num){
return (num & 1) == 0;
}
}
Here you are the main method which will be running as long as user is not entering -99;
You should include all your code in the while loop (even try/catch).
public static void main(String []args) {//begin main
Scanner input = new Scanner(System.in);
int number = 0;
//Keep application running as long as the input is not -99
while (number != -99){
//use try/catch method to test for invalid input
try{
//promt user to input a value
System.out.print("Enter a positive integer value: ");
number = input.nextInt();
//Start of if statement to test which to print and call of isEven method
//if the entered number is -99, the following code will skipped.
if(number == -99) continue;
if (isEven(number))
System.out.println("Your number is Even!");
else
System.out.println("Your number is Odd!");
}
//open catch method and print invalid
catch(Exception notNumber) {
System.out.println("Input not a number, try again.");
}
}
}
You could accept this answer, in case it is what you are looking for :)
My program is supposed to check if an integer is in a random integer. It will return true or false. For example: 45903 contains 4: true. For some reason; my code kept running after i entered the digit. Some thing is wrong with my containDigit() method but i can't seem to figure out. i'm very new to boolean.
import java.util.Scanner;
import java.util.*;
public class checkNum {
public static void main(String[] args) {
// Create a new Scanner object
Scanner console = new Scanner(System.in);
// Create a new Random objects
Random rand = new Random();
// Declare a integer value that is getting the value in the range of[10000, 99999]
int randomNum = rand.nextInt(90000)+10000;
// Show the random value to user by using of System.out.println
System.out.println(randomNum);
// Type a prompt message as "Enter a digit"
System.out.println("Enter a digit: ");
// Assign user input to integer value
int digit = console.nextInt();
// Define a boolean value that is assigned by calling the method "containDigit(12345,5)"
// Show the output
System.out.println(randomNum+ " contains" +
digit+" " + containDigit(randomNum,digit));
}
public static boolean containDigit(int first, int second) {
int digi = 10000;
// Define all statements to check digits of "first"
while (first > 0) {
digi = first % 10;
digi = first / 10;
}
if (digi == second){
return true;
}else {
return false;
}
// If it has "second" value in these digits, return true,
// If not, return false
// return a boolean value such as "return false";
return false;
}
}
If you're not restricted with way of solution, I can suggest below:
return (randomInt + "").contains(digit + "");
I dont understand why are you assigning first %10to digi and then immediately overwriting digi with first / 10.
Your while loop may never exit as first might always be greater than 0. It might never be entered as first might be equal to 0. You might want to do this:
while (first/10 == 0) {
first = first % 10;
if (first == second)
return true;
}
if(first%10 == second)
return true;
return false;
Your while loop never exits:
while (first > 0) {
digi = first % 10;
first = first / 10; // i believe this should be first instead of digit
}
You should add a simple print statement to check what your digit and first variables' values are:
System.out.println("digi: "+digi);
System.out.println("first: "+first);
I'm doing an assignment for school that requires us to find the largest of ten numbers. The numbers are between 0-9. I believe I got that part down. My problem is I'm trying to add an extra feature that is not required for the assignment. I am trying to get the loop to completely restart after the boolean statement is false and gives an error message. After I type the invalid value in, it gives the error message, but after I press "ok" it continues on to the next number. I want it to start back at the beginning of the loop.
Here's the code:
package Largest;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class LargestMain {
public static void main(String[] args) {
int number = 0;
String numStr = "";
int []myArray = new int[10];
int count = 1;
int largest = 0;
boolean valid = false;
while(valid == true); { // Loop to check validity
for(int i = 0; i < myArray.length; i++) {
myArray[i] = i + 1;
numStr = JOptionPane.showInputDialog("Please enter number " + count++ + ":");
number = Integer.parseInt(numStr); // Converts string value to integer
if(number >= largest) {
largest = number;
}
// If-Else if statements checks if values entered are equal to 0-9
if(number >= 0 && number <= 9) {
valid = true;
}
else if ((!(number >= 0 && number <= 9))) {
valid = false;
}
if (valid == false) {
JOptionPane.showMessageDialog(null, "INVALID INPUT...Try Again!!!", "Results", JOptionPane.YES_OPTION);
continue;
}
}
JOptionPane.showMessageDialog(null, "The Largest Number Is: " + largest, "Results", JOptionPane.PLAIN_MESSAGE);
}
}
}
I could just end the loop here by adding return:
if (valid == false) {
JOptionPane.showMessageDialog(null, "INVALID INPUT...Try Again!!!", "Results", JOptionPane.YES_OPTION);
return;
}
I just really want to learn how to restart the loop from the beginning. I tried search different topics, but none helped me solve my problem. Thanks for the help in advance!
To restart a loop, you would use the continue keyword. continue will skip to the next loop iteration.
When using a while loop, it'll simply restart the loop, since the loop doesn't end til valid is true. When using a for loop, itll skip to the next iteration (so if you're currently on index 5 and use continue, it'll move onto index 6 instead of staying at 5).
For nested loops, you can label the loop to specify which loop the statement is for:
firstloop:
while(valid) {
secondloop:
while(true) {
continue firstloop;
}
}
Also, no need for == true when checking a boolean. It could be represented as
while(valid) {
}
As for checking for false, valid == false, you'd use
while(!valid) {
}
Since you're a beginner and trying to learn, I have done a review of your code and enclosed some comments that might help you. I have posted updated code below.
Declarations: You should declare a variable in the innermost closure that requires it. Except largest, all other can go inside the for.
Your array variable did not make sense to have. Since you're keeping track of the largest as you go and not finding it at the end.
Control: Your /loop to check validity/ needs to be strictly around the input part, not your whole program, so you can repeat just the input statements till you're satisfied.
public static void main(String[] args)
{
int largest = 0;
for(int i = 1; i <= 10; i++)
{
boolean valid = false;
while (!valid)
{
String numStr = JOptionPane.showInputDialog("Please enter number " + i + ":");
int number = Integer.parseInt(numStr); //Converts string value to integer
if (number >= 0 && number <= 9)
{
valid = true;
}
else
{
JOptionPane.showMessageDialog(null, "INVALID INPUT...Try Again!!!", "Results", JOptionPane.YES_OPTION);
}
}
if (number > largest)
{
largest = number;
}
}
JOptionPane.showMessageDialog(null, "The Largest Number Is: " + largest, "Results", JOptionPane.PLAIN_MESSAGE);
}
You can use a labeled continue:
firstloop:
while(valid){
secondloop:
for(int i=0; i<10; i++{
//something
if(something){
continue firstloop;
}
}
}
See the documentation for more details.
UPDATE: Also... there is no need for the condition in the else part of your if/else statement. Just doing a else{ valid=false } would be equivalent to what you're doing right now. Another option would be to simplify it even further and skip the if/else part alltogether and just have:
valid = number >= 0 && number <= 9
Write a recursive function, that is, a function that calls itself.
public static void DoSomething()
{
// optionally ask the user for input at this point before processing begins.
while(yourCondition)
{
// do your stuff.
}
// when execution reaches here the condition is no longer valid; start over.
if(conditionToStartOver)
DoSomething(); // start again
}
Your logic is almost right but you shouldn't be looping on valid in the outer loop. Remember, you want to stop the inner loop when an input is invalid. Normally the outer loop would give the user an option to exit the program.
So for example:
while(true) {
boolean valid = true;
for(...; ...; ...) {
...
if(number < 0 || 9 < number) {
valid = false;
break;
}
}
if(valid) {
// show largest input dialog
} else {
// show invalid input dialog
}
// optionally ask the user if they want to exit
// if so, break
}
FYI: I am a beginner. Also, I understand that calling methods is a novice concept and there are a few threads like this already. My situation is a little different because I am very restricted by pseudo-code that my program must mirror identically. I am having trouble calling methods from other methods, including calling a method from inside main. Here is the pseudo-code followed by the code that I wrote:
PSEUDO-CODE:
// The user enters an integer and the program calculates that many primes
// It uses 3 methods, including the main. All the methods are in the same class
// and should be declared as ‘public static.’
Project Print the First n Primes
Package printTheFirstNPrimesPackage
Class PrintTheFirstNPrimes
Method Main
Declare numberOfPrimes as integer
Print “How many prime numbers do you want?"
Read numberOfPrimes from the keyboard
Call the method: PrintNPrimes(numberOfPrimes)
end Method (Main)
// ***********************************************************
// This method accepts an integer and prints that many prime
// numbers, starting at 2. 2 is the lowest primt number.
// ***********************************************************
Method void PrintNPrimes(int n)
declare i as integer
declare myNum as integer
myNum = 2 // The first prime number
i = 0
loop while i < n // This could be a ‘for’ loop
if IsPrime(myNum) // Call the Isprime method, (see below)
i = i + 1
print myNum
End If
myNum = myNum + 1
end loop
end Method PrintNPrimes
// **********************************************************
// This method accepts an integer and tests to see if it is
// a prime number. If it is prime, the method returns true,
// otherwise it returns false.
// **********************************************************
Method boolean IsPrime(int number)
Declare result as boolean
result = true
declare i as integer
i = 2
loop while i < number
if ((number % i) == 0)
result = false
exit loop
end if
end loop
return result
end Method
end Class
End Package
End Project
JAVA CODE:
package printTheFirstNPrimesPackage;
import java.util.*;
public class PrintTheFirstNPrimes {
public static void main(String [] args) {
int numberOfPrimes;
Scanner primes = new Scanner(System.in);
System.out.println("How many prime numbers do you want?");
numberOfPrimes = primes.nextInt();
// Call the method PrintNPrimes(numberOfPrimes)
}
public static void PrintNPrimes(int n) {
int i;
int myNum;
myNum = 2; // The first prime number
i = 0; {
while (i < n)
// if IsPrime(myNum) // Call the IsPrime method (see below) {
i = i + 1;
System.out.println(myNum);
myNum = myNum + 1;
}
}
public static boolean IsPrime(int number) {
boolean result;
result = true;
int i = 2;
while (i < number) {
if ((number % 1) == 0)
result = false;
}
return result;
}
}
My main issue is calling the IsPrime method within the if statement. I get an error saying the IsPrime cannot be converted from int to boolean which I knew, but the pseudo-code restricts me from doing much else. I also would like advice on how I should call the PrintNPrimes method within method main. Thanks.
Because your PrintNPrimes is static method, you can just call the method by passing the numberofPrimes.
Example:
public static void main(String [] args) {
int numberOfPrimes;
Scanner primes = new Scanner(System.in);
System.out.println("How many prime numbers do you want?");
numberOfPrimes = primes.nextInt();
PrintNPrimes(numberOfPrimes);
}
..........
Note: Java naming convention suggests that use first letter as small case letter while defining methods.
You can follow same approach to invoke other methods.
if IsPrime(myNum)
needs to be
if (IsPrime(myNum))
Also be sure to restore your curly braces. I don't see any reason why this will cause an error. Please post the exact error message if you still have problems.
Update code below with resolution for both (including if statement) of your compilation errors:
printNPrimes(numberOfPrimes);
if (isPrime(myNum)) // Call the IsPrime method (see below) {
Full updated code:
public static void main(String [] args) {
int numberOfPrimes;
Scanner primes = new Scanner(System.in);
System.out.println("How many prime numbers do you want?");
numberOfPrimes = primes.nextInt();
printNPrimes(numberOfPrimes);
}
public static void printNPrimes(int n) {
int i;
int myNum;
myNum = 2; // The first prime number
i = 0; {
while (i < n)
if (isPrime(myNum)) // Call the IsPrime method (see below) {
i = i + 1;
System.out.println(myNum);
myNum = myNum + 1;
}
}
public static boolean isPrime(int number) {
boolean result;
result = true;
int i = 2;
while (i < number) {
if ((number % 1) == 0)
result = false;
}
return result;
}
I didn't check the logic.