Running loop on Java method - java

So I have this assignment for class about doing something that implemented methods. I made this really simple program to give you a lucky number of the day. But for some reason, I couldn't get it to run properly more than twice.
The version I'm posting doesn't contain the loop, but I tried about 10 different ways and it just wouldn't work. Either it would keep spitting out numbers endlessly, or it would print out the welcome lines again instead of just the "would you like another number y/n" line. If someone could just help me figured out how I should have organized it so that the loop only displays this line:
Would you like to receive another number? y/n
and then if the user decides yes, the intro method runs again and that line displays again until uses presses "n"
here's the code:
import java.util.Scanner;
import java.math.BigInteger;
import java.util.Random;
public class MinOppgave2 {
public static void main(String[] args) {
menu();
}
public static void menu(){
//intro text
System.out.println("Welcome to lucky number of the day!");
System.out.println("What kind of number would you like today?");
intro();
Scanner input = new Scanner(System.in);
System.out.println("Would you like to receive another number? y/n");
String txtinput = input.nextLine();
if (txtinput.equalsIgnoreCase("y")){
intro();
}
else if (txtinput.equalsIgnoreCase("n")){
System.out.println("That's all for now, have a nice day!");
}
System.out.println("That's all for now, have a nice day!");
}
public static void intro(){
// user choice
Scanner input = new Scanner(System.in);
System.out.println("Please choose between: even odd or prime");
String text1 = input.nextLine();
//if/else user choice arguments
if (text1.equalsIgnoreCase("even"))
Evennum();
else if (text1.equalsIgnoreCase("odd"))
Oddnum();
else if (text1.equalsIgnoreCase("prime"))
Prime();
else
menu();
}
public static void Evennum(){
// random number generator
int num = 0;
Random rand = new Random();
num = rand.nextInt(1000) + 1;
while (!isEven(num)) {
num = rand.nextInt(1000) + 1;
}
System.out.println(num);
}
public static void Oddnum(){
// random number generator
int num = 0;
Random rand = new Random();
num = rand.nextInt(1000) + 1;
while (!isOdd(num)) {
num = rand.nextInt(1000) + 1;
}
System.out.println(num);
}
public static void Prime(){
// random number generator
int num = 0;
Random rand = new Random();
num = rand.nextInt(1000) + 1;
while (!isPrime(num)) {
num = rand.nextInt(1000) + 1;
}
System.out.println(num);
}
// prime checker
private static boolean isPrime(int numin){
if (numin <= 3 || numin % 2 == 0)
return numin == 2 || numin == 3;
int divisor = 3;
while ((divisor <= Math.sqrt(numin)) && (numin % divisor != 0))
divisor += 2;
//true/false prime answer
return numin % divisor != 0;
}
private static boolean isEven(int numin){
//math argument for even number
return (numin % 2) == 0;
}
private static boolean isOdd(int numin){
//math argument for even number
return (numin % 2) == 1;
}
}

Wrong recursion on the wrong place...
Try this:
public static void intro() {
System.out.println("Welcome to lucky number of the day!");
System.out.println("What kind of number would you like today?");
}
public static String takeInput() {
Scanner input = new Scanner(System.in);
return input.nextLine();
}
public static boolean pickNumber() {
System.out.println("Would you like to receive another number? y/n");
if (!takeInput().equalsIgnoreCase("y")) {
System.out.println("That's all for now, have a nice day!");
return false;
}
System.out.println("Please choose between: even odd or prime");
String chosen = takeInput();
//if/else user choice arguments
if (chosen.equalsIgnoreCase("even"))
Evennum();
else
if (chosen.equalsIgnoreCase("odd"))
Oddnum();
else
if (chosen.equalsIgnoreCase("prime"))
Prime();
return true;
}
public static void main(String[] args) {
intro();
while (pickNumber())
;
}

Related

how to make this code keep asking a number until finds a prime number?

I would like to have some ideas on how I can make this code to keep asking for a number until the program finds a prime number. Thank you so much :)
import java.util.Scanner;
class SieteDosEjerSeis {
public static void main(String args[])
{
int temp;
boolean isPrime=true;
Scanner scan= new Scanner(System.in);
System.out.println("Enter a number:");
//capture the input in an integer
int num=scan.nextInt();
scan.close();
for(int i=2;i<=num/2;i++)
{
temp=num%i;
if(temp==0)
{
isPrime=false;
break;
}
}
//If isPrime is true then the number is prime else not
if(isPrime)
System.out.println(num + " is a Prime Number");
else
System.out.println(num + " is not a Prime Number");
}
}
Well, mainly what everyone said, you need a Loop that stops when the number typed in the scanner is a prime number.
In this case I would say is better to have another method to check if N is prime or not, for a cleaner code.
✓ Tested
import java.util.Scanner;
public class SieteDosEjerSeis {
public static void main(String[] args) {
boolean prime = false;
// loop until prime is true
while(prime == false){
Scanner s = new Scanner(System.in);
System.out.println("Enter a number:");
int n = s.nextInt();
s.close();
// is it prime?
prime = isPrime(n);
if (prime){System.out.println(n + " is a prime number.");}
else{System.out.println(n + " is not a prime number.");}
}
}
// method that returns true or false depending if N is prime or not
public static boolean isPrime(int num) {
if (num <= 1) {return false;}
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) {return false;}
}
return true;
}
}
You can extract the prime evaluation to a new method:
class SieteDosEjerSeis {
public static boolean isPrime(int num) {
for (int i = 2; i <= num/2; i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
// ...
}
Then, change your IO code to be based on the result of this method:
class SieteDosEjerSeis {
// ...
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
for (;;) {
System.out.println("Enter a number:");
int num = scan.nextInt();
if (!isPrime(num)) {
System.out.println("The number is not prime!");
continue;
}
break;
}
// This will only be reached if the number is prime
System.out.println("The number is prime.");
}
}
You can use do while loop for this.
class SieteDosEjerSeis {
public static void main(String args[]) {
int temp;
boolean isPrime=true;
do {
Scanner scan= new Scanner(System.in);
System.out.println("Enter a number:");
//capture the input in an integer
int num=scan.nextInt();
scan.close();
for(int i=2;i<=num/2;i++) {
temp=num%i;
if(temp==0) {
isPrime=false;
break;
}
//If isPrime is true then the number is prime else not
if(isPrime)
System.out.println(num + " is a Prime Number");
else
System.out.println(num + " is not a Prime Number");
} while (!isPrime);
}
}

How to let the user attempt many times?

import java.util.Scanner;
import java.util.Random;
/*
* 1) the user can attempt many times and you need to display the number of successful attempt
* 2) the range of random number 1..49
* 3) output >> You successfully guess the number in 16 attempts
* 4) output >> Do you want to play again?
* */
public class GuessingGame {
public static void main(String[] args) {
Scanner uInput = new Scanner(System.in);
Random randNum = new Random();
int guessNumber, number, count=0;
String in;
char again;
System.out.println("Welcome to Guessing Game");
do {
number = randNum.nextInt(50); // random number in the range of 1..50
for(int i=0; i<5; i++)
{
System.out.println("Enter a number to guess: ");
guessNumber = uInput.nextInt(); // get guess number from user
if(guessNumber > number)
{
System.out.println("Too big");
}else if(guessNumber < number)
{
System.out.println("Too small");
}else
{
System.out.println("Success");
count+=1;
return;
}
}
System.out.println("You successfully guess the number in "+count);
System.out.println("Do you want to play again? ");
in = uInput.nextLine();
again = in.charAt(0); //again will hold the first character from in var
}while(again =='Y'|| again =='y');
System.out.println("Guessing game terminate, thank you");
}
}
public static void main(String[] args) {
System.out.println("Welcome to Guessing Game");
guessNumber();
System.out.println("Guessing game terminate, thank you");
}
private static void guessNumber() {
Scanner uInput = new Scanner(System.in);
Random randNum = new Random();
int guessNumber, number, count = 0;
String in;
char again;
boolean isCorrect = false;
number = randNum.nextInt(50); // random number in the range of 1..50
while (!isCorrect) {
System.out.println("Enter a number to guess: ");
guessNumber = uInput.nextInt(); // get guess number from user
count += 1;
if (guessNumber > number) {
System.out.println("Too big");
} else if (guessNumber < number) {
System.out.println("Too small");
} else {
System.out.println("Success");
isCorrect = true;
}
}
System.out.println("You successfully guess the number in " + count + " attempts");
System.out.println("Do you want to play again? yes/no");
in = uInput.next();
again = in.charAt(0); //again will hold the first character from in var
if (again == 'Y' || again == 'y') {
guessNumber();
}
}
All you have to do is to replace your do while loop with a while loop. But the point is that you must set an initial value 'Y' to your again char to start the while loop. the condition of the loop will be just the same. The code will be like : char again = 'Y';
while (again == 'Y' || again == 'y') {
System.out.println("Welcome to Guessing Game");
number = randNum.nextInt(50);
for (int i = 0; i < 5; i++) {
System.out.println("Enter a number to guess: ");
guessNumber = uInput.nextInt();
if (guessNumber > number) {
System.out.println("Too big");
} else if (guessNumber < number) {
System.out.println("Too small");
} else {
System.out.println("Success");
count += 1;
break;
}
}
System.out.println("You have successfully guessed the number for " + count + " times");
System.out.println("Do you want to play again? ");
in = uInput.next();
again = in.charAt(0); //again will hold the first character from in var
}
System.out.println("Guessing game terminate, thank you");
I must note that your count variable, contains the number of games which user has guessed the number successfully, and not the number of attempts during a single game. If you want to handle this too, create attempts variable inside the while loop and increase it whenever the user attempts.
Also I changed the line in = uInput.nextLine(); to in = uInput.next(); because I believe your scanner input will be skipped.

Issue implementing "More or less" game

So it seems like I have read all the posts and it just doesn't seem to work like I would like it to work? The code is supposed to check whether the number you input is the one given by RNG. Once the answer is correct I would like it to start over? Thank you guys!
import java.util.Scanner;
import java.lang.annotation.Repeatable;
import java.util.Random;
public class crs {
private static Scanner in;
public static void main(String[] args) {
// TODO Auto-generated method stub
Random rand = new Random();
int randno = rand.nextInt(100)+1;
int dig = 0;
do {
System.out.println("Number generated. Try your luck!: ");
dig = 0;
randno = rand.nextInt(100)+1;
//nextInt(int n) Returns a random integer value between 0 (inclusive) and n (exclusive),
while (dig!=randno) {
in = new Scanner(System.in);
dig = in.nextInt();
if (dig<randno) {
System.out.println("Too low!");
}else if (dig>randno) {
System.out.println("Too high!");
} else {
System.out.println("Correct!");
}}}
while(dig!=randno);
}}
Your code was a bit messy and the second loop was useless. I think this version should works better.
public static void main(String[] args)
{
Random rand = new Random();
int randno = rand.nextInt(100)+1;
int dig;
while(true)
{
System.out.println("Number generated. Try your luck!: ");
in = new Scanner(System.in);
dig = in.nextInt();
if (dig<randno)
{
System.out.println("Too low!");
}
else if (dig>randno)
{
System.out.println("Too high!");
}
else
{
System.out.println("Correct!");
break; // Stop the loop
}
}
}
Just put another while loop arround:
public static void main(String[] args) {
Random rand = new Random();
int randno, dig = 0;
while (true) {
System.out.println("Number generated. Try your luck!: ");
randno = rand.nextInt(100) + 1;
while (dig != randno) {
in = new Scanner(System.in);
dig = in.nextInt();
if (dig < randno) {
System.out.println("Too low!");
} else if (dig > randno) {
System.out.println("Too high!");
} else {
System.out.println("Correct!");
}
}
}
}
You also created the random number twice and had an unnecessary second loop.

How do I get this value passed into main properly?

i am having trouble passing the value of "guess" into my main method. The
method that is trying to return guess just shows up as zero in the main.I have tried various things such as void methods and different returns but the guess value does not get updated in the while loop of the main even though, from what i am seeing, it should be getting updated from the method and passing it down to the guesses right below it.
import java.util.*;
public class assignment052 {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
int userGuess = 0;
int compNum = 0;
int guess = 0;
int totalGuesses = 0; //
int best = 9999; //
introduction();
int games = 0;
String playAgain = "y";
while(playAgain.equalsIgnoreCase("y")) {
System.out.println();
System.out.println("I'm thinking of a number between 1 and 100...");
games++;
guessNumber(console, userGuess, compNum, guess);
System.out.println(guess);
totalGuesses += guess;
System.out.println("Do you want to play again?");
Scanner newGame = new Scanner(System.in);
playAgain = newGame.next();
if (best > guess) { //
best = guess; //
}
}
result(games, totalGuesses, best);
}
// Method that introduces the game
public static void introduction() {
System.out.println("This program allows you to play a guessing game.");
System.out.println("I will think of a number between 1 and");
System.out.println("100 and will allow you to guess until");
System.out.println("you get it. For each guess, I will tell you");
System.out.println("whether the right answer is higher or lower");
System.out.println("than your guess.");
}
// method to play 1 game
public static double guessNumber(Scanner console, int userGuess, int compNum, int guess) {
Random rand = new Random();
userGuess = console.nextInt();
guess = 1;
compNum = rand.nextInt(100)+1;
while(compNum != userGuess) {
if(compNum > userGuess) {
System.out.println("It's higher.");
} else {
System.out.println("It's lower.");
}
guess++;
userGuess = console.nextInt();
}
System.out.println("you got it right in " + guess + " guesses");
return guess;
}
// method for overall result
public static void result(int games, int totalGuesses, int best) {
System.out.println("Overall results:");
System.out.println();
System.out.println("Total games played : " + games);
System.out.println("Total guesses : " + totalGuesses);
System.out.println("Guesses per game : " + totalGuesses / games);
}
}

Making a lottery application: fill array with random numbers

I am making a lottery application in Java. My problem is that I think everything is in place and it (the IDE) is telling me that "int lotteryNumbersCount = Eck_LotteryClass.getLotteryNumbers().length;" needs to be static. So I change it to a static int and then I have to change it again in my class. Problem is when I finally run it I get all 0's for my random lottery data. Please help me find the errors in my ways. Total newb here and I've been looking online here but I want to try to figure it out without just copying code somewhere.
Eck_LotteryClass
import java.util.Random;
public class Eck_LotteryClass {
//instance field
private int lotteryNumbers [];
//Create random lottery numbers method array
public int [] getRandomNumbers(){
lotteryNumbers = new int [5];
Random r = new Random();
for(int i = 0; i < 5; i++)
lotteryNumbers[i] = r.nextInt(10);
return lotteryNumbers;
}
public int compareNumbers(int[] usersNumbers) {
int matchedNums = 0;
if (usersNumbers.length == lotteryNumbers.length) {
for (int i = 0; i < lotteryNumbers.length; i++) {
if (usersNumbers[i] == lotteryNumbers[i]) {
matchedNums ++;
}
}
}
return matchedNums;}
// Display the random lottery numbers for the user
public int [] getLotteryNumbers() {
return lotteryNumbers;
}
}
Eck_LotteryTester
import java.util.Scanner;
import java.util.Arrays;
public class Eck_LotteryTester{
public static void main(String[] args) {
Eck_LotteryClass lottery = new Eck_LotteryClass();
int lotteryNumbersCount = Eck_LotteryClass.getLotteryNumbers().length;
System.out.println("The Pennsylvania Lottery\n");
System.out.println("There are " + lotteryNumbersCount
+ " numbers in my lottery, they are 0 through 9. "
+ "See if you can win big CASH prizes!!!\n");
// Asks the user to enter five numbers.
Scanner keyboard = new Scanner(System.in);
int numbers[] = new int[lotteryNumbersCount];
for (int index = 0; index < numbers.length; index++) {
System.out.print(String.format("Enter Number %d: ", index + 1));
numbers[index] = keyboard.nextInt();
}
// Display the number of digits that match the randomly generated
// lottery numbers.
int match = lottery.compareNumbers(numbers);
if (match == lotteryNumbersCount) {
// If all of the digits match, display a message proclaiming the
// user a grand prize winner.
System.out.println("\nYOU WIN, GO SEE D. LEETE FOR YOUR GRAND PRIZE!!!");
} else {
System.out.println("\nThe winning numbers are " + Arrays.toString(Eck_LotteryClass.getLotteryNumbers()) +
"\nYou matched " + match + " number(s).");
}
}
}
Change
int lotteryNumbersCount = Eck_LotteryClass.getLotteryNumbers().length;
to
int lotteryNumbersCount = lottery .getLotteryNumbers().length;
and you won't have to change the methods signature to static. Also you'll be talking about the same variable.
Also change
// Display the random lottery numbers for the user
public int [] getLotteryNumbers() {
return lotteryNumbers;
}
to
// Display the random lottery numbers for the user
public int [] getLotteryNumbers() {
return getRandomNumbers();
}
So the array gets initialized. And changing the signature of
public int [] getRandomNumbers
to
private int [] getRandomNumbers
wouldn't hurt
package New_list;
import java.util.Scanner;
import java.util.Random;
public class Lottery {
private static Scanner scan;
public static void main(String[] args) {
System.out.println("\t\t\tWelcome to Harsh Lottery System.\n");
Random random = new Random();
int lottery_win_1 = random.nextInt(10);
// Print Lottery winning number...1 :P
// System.out.println(lottery_win_1 + "\n");
int lottery_win_2 = random.nextInt(10);
// Print Lottery winning number...2 :P
// System.out.println(lottery_win_2 + "\n");
boolean loop = true;
while(loop){
System.out.println("\t\t\tEnter your 2 Digit Lottery number.\n");
scan = new Scanner(System.in);
int lottery_no = scan.nextInt();
if ((lottery_no >= 0) && (lottery_no <= 99)) {
int lottery_no_1, lottery_no_2;
if (lottery_no > 9) {
lottery_no_1 = lottery_no / 10;
lottery_no_2 = lottery_no % 10;
} else {
lottery_no_1 = 0;
lottery_no_2 = lottery_no;
}
if ((lottery_win_1 == lottery_no_1)
&& (lottery_win_2 == lottery_no_2)) {
System.out
.println("\t\t\tCongratulation you win lottery,and you win $10000.\n");
} else if ((lottery_win_1 == lottery_no_2)
&& (lottery_win_2 == lottery_no_1)) {
System.out
.println("\t\t\tCongratulation your inverse no is lottery winer number so that you win $4000.\n");
} else if ((lottery_win_1 == lottery_no_1)
|| (lottery_win_1 == lottery_no_2)
|| (lottery_win_2 == lottery_no_1)
|| (lottery_win_2 == lottery_no_2)) {
System.out
.println("\t\t\tCongratulation your one digit from your lotter number match to the lottery winner.so you win $1000.\n");
} else {
System.out.println("\t\t\tSorry,Please try again\n");
System.out.println("\t\t\tDo you want to try again\n\t\t\tPress 1 for Continue\n\t\t\tPress 2 for exit\n");
int ch = scan.nextInt();
switch(ch){
case 1: System.out.println("\t\t\tOk...Try again\n");
break;
case 2: System.out.println("\t\t\tBbye... See you later\n");
loop = false;
break;
}
}
} else {
System.out.println("\t\t\tSorry,Please choose 2 digit number\n");
}
}
}
}

Categories