Issue implementing "More or less" game - java

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.

Related

how can i Use bets(if) for ReadKey in java

I'm a beginner java developer. I want to build a program that gets a number from the user, then say it's prime or not.
Java code:
import java.util.Scanner;
import static java.lang.System.out;
public class prime
{
public static boolean prime(int n)
{
for(int i = 2; i <n ; i++)
{
if(n % i == 0){
return false;
}
}
return true;
}
public static void main(String[]args)
{
Scanner input = new Scanner(System.in);
out.println("enter a number: ");
int x = input.nextInt();
if(prime(x)){
out.println(x + "is a prime number");
}else{
out.println(x + "isn't a prime number");
}
}
}
However, I want to declare a bool variable, then ask the user if they want to continue, the user then says yes or no. I have already written this code in C#:
C# code
class Program
{
static bool prime(int n)
{
for(int i = 2; i < n ; i++)
{
if(n % i == 0)
‌{
return false;
}
}
return true;
}
static void main(String[]args)
{
Bool permit = true;
While(permit)
{
Console.WriteLine(“enter a number”)
int x = int.Parse(Console.ReadLine());
if(prime(x))
{
Console.WriteLine(x + "is a prime number");
}
else
{
Console.WriteLine(x + " isn't a prime number");
}
Console.WriteLine(“do you want to continue”);
Permit = Console.ReadKey.Key() == ConsoleKey.Y?true:false;
}
}
}
How can I build it in Java?
You can't directly map your C# keyboard key press detection to Java.
AFAIK, checking which key is pressed can only be done via key listeners in Java AWT/Swing GUI programs [How to Write a Key Listener]. Your program, however, is a console program and Java doesn't have any mechanisms to detect which key was pressed in a console application. See this question for more info.
Now what you could do is read the String that a certain key press produced. Something like this:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean permit = true;
while (permit) {
// your existing code
out.println("do you want to continue?");
permit = input.next("y|Y").equalsIgnoreCase("y");
}
}
I also corrected prime method.
import java.util.Scanner;
import static java.lang.Math.abs;
import static java.lang.System.out;
public class Prime {
public static boolean prime(int n) {
for (int i = 2; i < n/2; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
while (true) {
try {
out.println("enter a number: ");
int x = Integer.parseInt(input.nextLine());
if (prime(x)) {
out.println(x + " is a prime number");
} else {
out.println(x + " isn't a prime number");
}
} catch (NumberFormatException e) {
System.out.println("NumberFormatException");
}
out.println("do you want to continue");
if (!input.nextLine().equals("Y")) break;
}
}
}
Just check if the key pressed is the y (yes) and if yes it continues in the cycle.
static void main(String[] args)
{
ConsoleKey response;
do
{
Console.WriteLine("enter a number");
int x = int.Parse(Console.ReadLine());
if (prime(x)) {
Console.WriteLine(x + " is a prime number");
} else {
Console.WriteLine(x + " isn't a prime number");
}
Console.Write("do you want to continue? [y/n] ");
response = Console.ReadKey(false).Key;
}
while (response == ConsoleKey.Y);
}

How to repeat "if" statement when output is false

I am working on a simple game in which the user has to guess a random number. I have all the code set up except for that fact that if the guess is too high or too low I don't know how to allow them to re-enter a number and keep playing until they get it. It just stops; here is the code:
import java.util.Scanner;
import java.util.Random;
public class Test {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Random rand = new Random();
int random = rand.nextInt(10) + 1;
System.out.print("Pick a number 1-10: ");
int number = input.nextInt();
if (number == random) {
System.out.println("Good!");
} else if (number > random) {
System.out.println("Too Big");
} else if (number < random) {
System.out.println("Too Small");
}
}
}
In order to repeat anything you need a loop.
A common way of repeating until a condition in the middle of loop's body is satisfied is building an infinite loop, and adding a way to break out of it.
Idiomatic way of making an infinite loop in Java is while(true):
while (true) {
System.out.print("Pick a number 1-10: ");
int number = input.nextInt();
if (number == random) {
System.out.println("Good!");
break; // This ends the loop
} else if (number > random) {
System.out.println("Too Big");
} else if (number < random) {
System.out.println("Too Small");
}
}
This loop will continue its iterations until the code path reaches the break statement.
You need to use a loop for that. The code should work like this:
import java.util.Scanner;
import java.util.Random;
public class Test {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Random rand = new Random();
int random = rand.nextInt(10) + 1;
System.out.print("Pick a number 1-10: ");
int number = input.nextInt();
boolean found = false;
while (!found) {
if (number == random) {
System.out.println("Good!");
found = true;
} else if (number > random) {
System.out.println("Too Big, try again:");
number = input.nextInt();
} else if (number < random) {
System.out.println("Too Small, try again:");
number = input.nextInt();
}
}
}
}
You could use a do...while.
Random rand = new Random();
int random = rand.nextInt(10) + 1;
do {
Scanner input = new Scanner(System.in);
System.out.print("Pick a number 1-10: ");
int number = input.nextInt();
if (number == random) {
System.out.println("Good!");
} else if (number > random) {
System.out.println("Too Big");
} else if (number < random) {
System.out.println("Too Small");
}
} while ( number != random );
Several techniques exist to loop your request, among them:
while (<condition>) { <do something> }
do { <something> } while (<condition>);
for (<init statement>, <condition>, <update statement>) { <do something> }
To show off, you can avoid using one of the above explicit loop constructs by using recursion:
mport java.util.Scanner;
import java.util.Random;
public class Test {
public static void ask(int random) {
Scanner input = new Scanner(System.in);
System.out.print("Pick a number 1-10: ");
int number = input.nextInt();
if (number == random) {
System.out.println("Good!");
} else if (number > random) {
System.out.println("Too Big");
ask(random);
} else if (number < random) {
System.out.println("Too Small");
ask(random);
}
}
public static void main(String[] args) {
Random rand = new Random();
int random = rand.nextInt(10) + 1;
ask(random);
}
}
Here the ask() method keeps calling itself, until the end condition (user guessed right) is reached.
Depending on the cleverness of the Java virtual machine this might stress the call stack, or not.
Enclose the if statements within a do-while loop, that will loop around while the user hasn't guessed the number:
int number;
do {
System.out.print("Pick a number 1-10: ");
number = input.nextInt();
if (number == random) {
System.out.println("Good!");
} else if (number > random) {
System.out.println("Too Big");
} else if (number < random) {
System.out.println("Too Small");
}
} while (number != random);
In order to repeat code conditionally, use a loop.
// this code will execute only once
System.out.print("Pick a number 1-10: ");
// initialize number to a value that would not be used and not equal random
int number = -1;
// the code inside the curly braces will repeat until number == random
while (number != random) {
// get next number
number = input.nextInt();
// handle case one
if(number > random) System.out.println("Too Big");
// handle case two
if(number < random) System.out.println("Too Small");
}
// once number == random, the condition is false so we break out of the loop
System.out.println("Good!");
What you're looking for are constructs in the programming language that allow you do a specific thing again and again.
This is done using loops.
Check the docs for the while loop for instance. That's what you need.

Running loop on Java method

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())
;
}

Creating a guessing game

I am following a mooc in which I have to create a guessing game. I kind of understand the problem but I have no clue how to fix it.
The problem is that for the method "loop" numberDrawn isn't a defined integer. But I define it in the main argument body where "loop" is placed so how come "loop" doesn't see that I defined it already.
import java.util.Random;
import java.util.Scanner;
public class GuessingNumberGame {
private static int drawNumber() {
return new Random().nextInt(101);
}
public static void main(String[] args) {
Scanner reader = new Scanner(System. in );
System.out.println("Guess a number: ");
int num = Integer.parseInt(reader.nextLine());
int numberDrawn = drawNumber();
if (numberDrawn > num) {
System.out.println("The number is greater");
loop();
} else if (numberDrawn < num) {
System.out.println("The number is lesser");
loop();
} else {
System.out.println("Congratulations, your guess is correct!");
}
}
public static void loop() {
Scanner reader = new Scanner(System. in );
System.out.println("Guess a number: ");
int num = Integer.parseInt(reader.nextLine());
if (numberDrawn > num) {
System.out.println("The number is greater");
loop();
} else if (numberDrawn < num) {
System.out.println("The number is lesser");
loop();
} else {
System.out.println("Congratulations, your guess is correct!");
}
}
}
The issue is that numberDrawn is local to main(), and is inaccessible from loop(). The variable cannot be used in loop() unless it is passed.
However, it seems to me like the second loop() function is unnecessary and will create recursive loops. I modified main() to work properly and contain a loop:
import java.util.Random;
import java.util.Scanner;
public class GuessingNumberGame {
private static int drawNumber() {
return new Random().nextInt(101);
}
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
while(true) {
System.out.println("Guess a number: ");
int num = Integer.parseInt(reader.nextLine());
int numberDrawn = drawNumber();
if (numberDrawn > num) {
System.out.println("The number is greater");
} else if (numberDrawn < num) {
System.out.println("The number is lesser");
} else {
break;
}
}
System.out.println("Congratulations, your guess is correct!");
}
The Problem is you have defined your "numberDrawn" variable in a method ,variables defined in the method are local to the method. Just define your variable at variable declarations and make it static.
import java.util.Random;
import java.util.Scanner;
public class GuessingNumberGame {
static int numberDrawn=0;
private static int drawNumber() {
return new Random().nextInt(101);
}
public static void main(String[] args) {
Scanner reader = new Scanner(System. in );
System.out.println("Guess a number: ");
int num = Integer.parseInt(reader.nextLine());
numberDrawn= drawNumber();
if (numberDrawn > num) {
System.out.println("The number is greater");
loop();
} else if (numberDrawn < num) {
System.out.println("The number is lesser");
loop();
} else {
System.out.println("Congratulations, your guess is correct!");
}
}
public static void loop() {
Scanner reader = new Scanner(System. in );
System.out.println("Guess a number: ");
int num = Integer.parseInt(reader.nextLine());
if (numberDrawn > num) {
System.out.println("The number is greater");
loop();
} else if (numberDrawn < num) {
System.out.println("The number is lesser");
loop();
} else {
System.out.println("Congratulations, your guess is correct!");
}
}
}
This won't work because main() is also considered as a different method in Java and all the variables defined in main() is not accessible to external methods directly ie. loop() in your case. One solution is passing the variable numberdrawn as an argument to the method. Another is you can define the variable numberdrawn outside the main method.
try this, declare ur variable at class level like this:
public class GuessingNumberGame {
private static int numberDrawn;
in ur main();
int num = Integer.parseInt(reader.nextLine());//no change here
numberDrawn = drawNumber();//remove int keyword

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