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
Related
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);
}
}
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);
}
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.
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())
;
}
how would you restructure this code so it doesnt use continue and break? i have tried but have had no luck. thanks
import java.util.*;
public class q6 {
public static void main(String args[]) {
int Number;
Scanner sc = new Scanner(System.in);
while (true) // seemingly an infinite loop
{
System.out.print("Enter a positive integer ");
System.out.println("or 0 to exit ");
Number = sc.nextInt();
if (Number == 0)
break;
else if (Number < 0);
System.out.print("Squareroot of " + Number);
System.out.println(" = " + Math.sqrt(Number));
//continue lands here at end of current iteration
}
//break lands here
System.out.println("a zero was entered");
}
}
import java.util.*;
public class q6 {
public static void main(String args[]) {
int Number;
Scanner sc = new Scanner(System.in);
System.out.print("Enter a positive integer ");
System.out.println("or 0 to exit ");
Number = sc.nextInt();
while (Number>0)// looping while number >0
{
System.out.print("Squareroot of " + Number);
System.out.println(" = " + Math.sqrt(Number));
Number = sc.nextInt();
}
System.out.println("a zero was entered");
}
import java.util.*;
class q6 {
public static void main(String args[]) {
int Number;
Scanner sc = new Scanner(System.in);
while (instruct() && (Number=sc.nextInt())!=0) // seemingly an infinite loop
{
if (Number < 0);
System.out.print("Squareroot of " + Number);
System.out.println(" = " + Math.sqrt(Number));
//continue lands here at end of current iteration
}
//break lands here
System.out.println("a zero was entered");
}
static boolean instruct()
{
System.out.print("Enter a positive integer ");
System.out.println("or 0 to exit ");
return true;
}
}