I'm new to programming and I'm making a guessing game where the program randomly generates a number between 1 and 10, the user then is asked to guess what the number is, the user should be able to keep guessing until he guesses correctly and the system asks them if they want to play again,
In my code I've printed the number that the system has randomly generated so that it is quicker to complete the game whilst testing. When I try and execute the program and enter the number that the system has generated the message that they are correct and asking if they want to play again does not come up.
Any help would be greatly appreciated!
Thank you in advance,
(Also, anything wrong with this question just tell me, it's my first time asking on here)
Here is my code,
import java.util.Scanner;
import java.util.Random;
public class GuessingGame1 {
public static int randomizer() {
Random rand = new Random();
int num = rand.nextInt(10)+1;
System.out.println(num);
int count = 0;
return num;
}
public static int userInput() {
System.out.println("I've thought of a number between 1 and 10");
System.out.println("Enter your guess...");
Scanner scan = new Scanner(System.in);
int guess = scan.nextInt();
return guess;
}
public static String compare() {
int count = 0;
String result = null;
if (userInput() == randomizer()) {
System.out.println("You guessed it - I was thinking of " + randomizer());
count++;
result = "It took you " + count + " guesses.";
return result;
}
else if (userInput() > randomizer()) {
result = "Lower!";
count++;
return result;
}
else if (userInput() < randomizer()) {
result = "Higher";
count++;
}
return result;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Scanner scanLine = new Scanner(System.in);
String playAgain = "";
do {
randomizer();
do {
userInput();
compare
} while (userInput() != randomizer());
System.out.println("Play again? Yes/No");
playAgain = scanLine.nextLine();
} while (playAgain.equalsIgnoreCase("yes") || playAgain.equalsIgnoreCase("y"));
}
}
The problem is that you call twice to Randomizer!
call randomizer once as parameter to compare and return boolean from compare for a match.
You must change your methods something like this
public static String compare(int a,int b) {
int count = 0;
String result = null;
if (a == b) {
System.out.println("You guessed it - I was thinking of " + b);
count++;
result = "It took you " + count + " guesses.";
return result;
}
else if (a > b) {
result = "Lower!";
count++;
return result;
}
else if (a < b) {
result = "Higher";
count++;
}
return result;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Scanner scanLine = new Scanner(System.in);
String playAgain = "";
int a;
int b;
do {
do {
a=userInput();
b= randomizer();
System.out.println(compare(a,b));
} while (a != b);
System.out.println("Play again? Yes/No");
playAgain = scanLine.nextLine();
} while (playAgain.equalsIgnoreCase("yes") || playAgain.equalsIgnoreCase("y"));
}
}
you have left the () in compare and the count will always be zero as it is been initialized when the compare function is called.
Related
I wanted to write a small quiz with an int calculation, but I can not get it to run.
import java.util.Scanner;
public class Quiz {
public static void main(String[]args) {
Scanner scan = new Scanner(System.in);
int a = 4;
int b = 4;
String in;
in= scan.nextLine();
System.out.println("What is 4+4?");
if (in.equals (a+b)) {
System.out.println("Correct");
}else {
System.out.println("Wrong");
}
}
}
You can use scan.nextInt(); to accept int values,
Scanner scan = new Scanner(System.in);
int a = 4;
int b = 4;
int in= scan.nextInt();
System.out.println("What is 4+4?");
if (in == (a+b)) {
System.out.println("Correct");
}else {
System.out.println("Wrong");
}
First of all why would you add two numbers when you can keep one number in a variable as the expected result. The input expects a String so you can either change it to int or say String.valueOf(expected result)
int in= scan.nextInt();
Scanner scan = new Scanner(System.in);
final int a = 8;
System.out.println("What is 4+4?");
String in= scan.nextLine();
if (in.equals(String.valueOf(a))) {
System.out.println("Correct");
}else {
System.out.println("Wrong");
}
}
}
Although others suggest using Scanner#nextInt I wouldn't recommend it. It has some kind of nonintuitive behavior and causes harm when used by programmers who are new to Java when trying to read first number, the operator and the second number.
As the OP is already familiar with Scanner#nextLine I would suggest the following approach:
Scanner sc = new Scanner(System.in);
String a = sc.nextLine();
String b = sc.nextLine();
int first = Integer.parseInt(a);
int second = Integer.parseInt(b);
int result = first+second;
To design such quiz, I would suggest going a bit further:
public static void main(String[] args) {
Random random = new Random();
Scanner sc = new Scanner(System.in);
int a = random.nextInt(100);
int b = random.nextInt(100);
System.out.println(String.format("What is the result of %d + %d", a, b));
String answer = sc.nextLine();
try {
int result = Integer.parseInt(answer);
if (result == a+b) {
System.out.println("Correct");
} else {
System.out.println("Wrong");
}
} catch (NumberFormatException e) {
System.out.println(answer + " - is not a valid number");
}
}
You need to convert the String value of the the scanner to an int, you can use scan.nextInt() as well but this can lead to problems later with the scanner not progressing to the next line after the int. You also need to order it correctly otherwise it'll ask for input before the question is asked. See below, hope it helps.
import java.util.Scanner;
public class Quiz {
public static void main(String[]args) {
Scanner scan = new Scanner(System.in);
int a = 4;
int b = 4;
int in;
System.out.println("What is 4+4?");
in = Integer.valueOf(scan.nextLine());
if (in == (a+b)) {
System.out.println("Correct");
}else {
System.out.println("Wrong");
}
}
}
String in = scan.nextLine();
if (in.equals(String.valueOf(a+b))) {
System.out.println("Correct");
}else {
System.out.println("Wrong");
}
Or use Integer.toString(a+b) or "" + (a + b)
Or change Integer in = scan.nextInt()
I am trying to make a match game where random numbers will show on the console then you have to type back the same numbers. I am having a problem with the if statement where it shows incorrect even when I input the right numbers. Here is my code so far:
package MatchGame;
import java.util.Random;
import java.util.Scanner;
public class match2 {
int a;
int b;
int c;
int d;
String countdown[] = {
"3...",
"2...",
"1..."
};
public match2() throws InterruptedException {
set1();
}
public void set1() throws InterruptedException {
Scanner s = new Scanner(System.in);
System.out.println("press ENTER for your first set...");
s.nextLine();
for (int i = 0; i < countdown.length; i++) {
Thread.sleep(1000);
System.out.println(countdown[i]);
}
a = number();
b = number();
c = number();
d = number();
System.out.print(a);
System.out.print(b);
System.out.print(c);
System.out.print(d);
int set = a + b + c + d;
int guess = s.nextInt();
{
if(set == guess) {
System.out.println("Nice bruh +1");
}
else {
System.out.println("Nope");
}
}
}
public static int number(){
Random r = new Random();
int match = r.nextInt(9) + 1;
//rv = rv + match;
return match;
}
}
Also the variable 'set' doesn't seem to include the variables a, b, c, and d in it.
An easy method would be to store your values and input to two arrays two separate arrays and compare both instead.
This question already has answers here:
Examples of Recursive functions [closed]
(22 answers)
Closed 5 years ago.
I am a student currently using java and I am having a hard time programming a high and low guessing game. I cannot use looping or "while" code. Any thoughts? This is what I have as of now:
public class FinalProject1
{
public static void main(String [] args)
{
System.out.println("Number Guessing Game 1-1000\nGuess a number");
guess();
}
public static int random()
{
int x = (int)(1000*Math.random() + 1);
return x;
}
public static void guess()
{
int num = random();
int tries = 0;
Scanner keyboard = new Scanner(System.in);
String inputString = keyboard.nextLine();
int input = Integer.parseInt(inputString);
if (input > num)
{
System.out.println("Guess a higher number");
inputString = keyboard.nextLine();
}
else if (input < num)
{
System.out.println("Guess a lower number");
inputString = keyboard.nextLine();
}
else if (num == input)
{
System.out.println("You Win");
}
}
}
A few things..
Your > & < checks for higher and lower are backwards
You need to be using recursion in order to produce your intended behavior without any loops.
public static void main(String [] args)
{
System.out.println("Number Guessing Game 1-1000\nGuess a number");
int num = random();
Scanner keyboard = new Scanner(System.in);
guess(keyboard, num);
}
public static int random()
{
int x = (int)(1000*Math.random() + 1);
return x;
}
public static void guess(Scanner keyboard, int goal)
{
String inputString = keyboard.nextLine();
int input = Integer.parseInt(inputString);
if (input < goal)
{
System.out.println("Guess a higher number");
guess(keyboard, goal);
}
else if (input > goal)
{
System.out.println("Guess a lower number");
guess(keyboard, goal);
}
else if (input == goal)
{
System.out.println("You Win");
}
}
Basically what's happening is that we are getting their response and checking if it's > or < the result, telling them, and the immediately calling the guess() method again in order to repeat this process until they get it right.
Wrapping your head around recursion can be fairly difficult in the beginning, just keep practicing
First, your logic is flawed. If input > num then user guessed too high, and needs to guess a lower number.
Others have suggested to use recursion, and that's the common solution for your problem, and is likely what you need to do, since you likely have just learned about recursion.
But, since I like to be contrary, I'd do it by starting a new thread, like this:
public class FinalProject1 implements Runnable {
private Scanner keyboard = new Scanner(System.in);
private int num = random();
public static void main(String[] args) {
System.out.println("Number Guessing Game 1-1000\nGuess a number");
new Thread(new FinalProject1()).start();
}
public static int random() {
return (int) (1000 * Math.random() + 1);
}
#Override
public void run() {
String inputString = this.keyboard.nextLine();
int input = Integer.parseInt(inputString);
if (input > this.num) {
System.out.println("Guess a lower number");
new Thread(this).start();
} else if (input < this.num) {
System.out.println("Guess a higher number");
new Thread(this).start();
} else if (this.num == input) {
System.out.println("You Win");
}
}
}
I am trying to write a method that calculates the sum of odd integers between 1 and a given positive integer n, without using anything else than if statements (sheesh!). It worked out just fine until I decided to also create a method that would ask recursively for the number until it was positive and use it to get n.
Now my program outputs the correct results until I enter a negative number. It then asks for a postive one until I enter one and it outputs 0, the value I initialised the variable val with.
I'm not sure where the logic error is. Could you please take a look? I'm sure it's something obvious, but I guess I have just reached the end of my wits today. Thanks!
package oddsum;
import java.util.Scanner;
public class Oddsum {
public static int oddSum(int n){
int val=0;
if(n>1){
if(n%2==0){
val=n+oddSum(n-1);
}else{
val=oddSum(n-1);
}
}
return val;
}
public static int request(int n){
Scanner in= new Scanner(System.in);
System.out.println("Give me a positive integer: ");
n=in.nextInt();
if (n<0){
System.out.println("I said positive! ");
request(n);
}
return n;
}
public static void main(String[] args) {
int val=0;
int n=request(val);
System.out.println(oddSum(n));
}
}
You should remove input parameter from your request() method. Because your negative input is carried out through the recursive call.
public class Oddsum {
public static int oddSum(int n) {
int val = 0;
if (n > 1) {
if (n % 2 == 0) {
val = n + oddSum(n - 1);
} else {
val = oddSum(n - 1);
}
}
return val;
}
public static int request() {
Scanner in = new Scanner(System.in);
System.out.println("Give me a positive integer: ");
int n = in.nextInt();
if (n < 0) {
System.out.println("I said positive! ");
return request();
}
return n;
}
public static void main(String[] args) {
int n = request();
System.out.println(oddSum(n));
}
}
Output;
I am making a very simple blackjack game with one class and at least 2 methods. I want to take the random generated numbers that are being output (cards being dealt) and add them so I can make an if else statement to check if the total is over 21 causing the player to lose.
import java.util.*;
public class BlackJack {
private Scanner scan;
static Random generator = new Random();
public BlackJack(){
scan = new Scanner (System.in);
}
public static void main(String[] args) {
StarterCards();
Hit();
}
public static void Hit() {
System.out.println("Hit? (y or n)");
String yes = new String ("y");
Scanner input = new Scanner(System.in);
String yesorno = input.nextLine();
if(yesorno.equals(yes)) {
RandomCard();
Hit();
if()
} else {
System.out.println("Game Over");
}
}
public static void RandomCard() {
int card = generator.nextInt(10) + 1;
System.out.println("Card : "+ card);
int total2 = card;
}
public static void StarterCards() {
int card1 = generator.nextInt(10) + 1;
int card2 = generator.nextInt(10) + 1;
System.out.println("Card : "+ card1);
System.out.println("Card : "+ card2);
}
}
Re:
How to take integers being printed by a method?
The solution: don't have the method print anything. Instead have the method return the number, and let the calling code print it or do with the number whatever it wants to do.
i.e.,
public int myMethod() {
int someNumber = ....; // calculate it here
// System.out.println(someNumber); // don't print it here!
return someNumber
}