I want to create a program that gives you three tries to find any given number. It's going to essentially be a guessing game. The problem is, I have to do this without any loops. So far, I'm only able to get input from the user, read that input and tell them if they've won or 'lost' the game. The program only runs once and stops(as expected).
I was told that it could be done without loops, albeit with a lot more code. Can you guys let me know what I'm doing wrong here and give me some pointers on what I should change? If you need clarification let me know.
Thanks.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner ran = new Scanner(System.in);
System.out.println("Enter a number: ");
int x = ran.nextInt();
if (x < 3) {
System.out.println("Too low. Try again.");
System.out.println("Enter a number: ");
} else if (x > 3) {
System.out.println("Too high. Try again");
} else if(x == 3) {
System.out.println("You win. Nice job.");
} else {
System.out.println("You lose");
}
System.out.println("Number Guessing Game (c) 2017 Anna Gibson");
}
}
You can do this using recursion. See this program. Find explanations within comments.
import java.util.Scanner;
public class HelloWorld {
private static Scanner ran = new Scanner(System.in);
//this is number of tries you want to give to user
private static int counter = 5;
//The actual number
private static final int NUM = 3;
public static boolean guessingMachine() {
//counter indicates that number of attempts remaining
if(counter == 0) {
return false;
}
counter--;
System.out.println("Enter a number: ");
int x = ran.nextInt();
if (x < NUM) {
System.out.println("Too low. Try again.");
//try again... call this method again
return guessingMachine();
} else if (x > NUM) {
System.out.println("Too high. Try again");
//try again... call this method again
return guessingMachine();
} else {
//x == NUM success
return true;
}
}
public static void main(String[] args) {
boolean result = guessingMachine();
if(result)
System.out.println("You win. Nice job.");
else
System.out.println("You lose");
System.out.println("Number Guessing Game (c) 2017 Anna Gibson");
}
}
You could next conditions:
get user input
if input is correct, congratulation user and exit
else
get user input //second attempt
if input is correct, congratulation user and exit
...
You can continue from there. The code you provided, where you tell the user if they are too high or low, would have to be included in each of the branches of the pseudocode above.
I think the main purpose of this exercise is intended for you to strengthen your nested if-else concepts.
import java.util.Scanner;
public class HelloWorld{
public static void main(String []args){
int num=3;
int count=1;
Scanner ran = new Scanner(System.in);
System.out.println("Enter a number: ");
int x = ran.nextInt();
if(x>num || x<num)
{
System.out.println("incorrect guess");
count++;
System.out.println("Enter a number: ");
x = ran.nextInt();
if(x>num || x<num)
{
System.out.println("incorrect guess");
count++;
System.out.println("Enter a number: ");
x = ran.nextInt();
if(x>num || x<num)
{
System.out.println("incorrect guess YOU LOSE");
}
else
{
System.out.println("YOU WIN");
}
}
else
{
System.out.println("YOU WIN");
}
}
if(x==num && count==1)
{
System.out.println("YOU WIN");
}
System.out.println("Number Guessing Game (c) 2017 Anna Gibson");
}
}
import java.util.*;
public class TestProject
{
public static void theMath()
{
double add = 1;
double subtract = 2;
double multiply = 3;
double divide = 4;
#SuppressWarnings("resource")
Scanner input = new Scanner(System.in);
//Pick first number
System.out.println("Please enter a number: ");
int intOne = input.nextInt();
// Pick second number
System.out.println("Please enter another number: ");
int intTwo = input.nextInt();
//User chooses operator
System.out.println("Now please choose an operator (1 for add, 2 for subtract, 3 for mulitply, 4 for divide): ");
int userChoice = input.nextInt();
// Add
if (userChoice == add)
System.out.println("Your answer is: " + (intOne + intTwo));
// Subtract
else if (userChoice == subtract)
System.out.println("Your answer is: " + (intOne - intTwo));
// Multiply
else if (userChoice == multiply)
System.out.println("Your answer is: " + (intOne * intTwo));
// Divide
else if (userChoice == divide)
System.out.println("Your answer is: " + (intOne / intTwo));
// If wrong input
else
{
System.out.println("Nothing happens!");
System.out.println("Please make sure you entered a number and an operator.");
}
}
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
theMath();
System.out.println("Would you like to do another calculation?");
String redo = input.nextLine();
if(redo.equals("yes"))
theMath();
else if(redo.equals("no"))
System.out.println("Thanks for calculating with me! It certainly was fun!");
else
System.out.println("Please enter 'yes' or 'no' only.");
String yesNo = input.nextLine();
if(yesNo.equals("yes"))
theMath();
else
System.out.println("Thanks for calculating with me! It certainly was fun!");
}
}
I was wondering how I could recall the main method an infinite amount of times if I wanted to. What I was doing was just copying and pasting it over and over again but there has to be a better way. And also, I would like to know how to return a value has a decimal(so I could do 25/6 and get the correct answer).
Why not put only the statements that should be repeated inside a loop?
String redo;
do{
System.out.println("Would you like to do another calculation?");
redo = input.nextLine();
if(redo.equals("yes"))
theMath();
else if(redo.equals("no"))
System.out.println("Thanks for calculating with me! It certainly was fun!");
else
System.out.println("Please enter 'yes' or 'no' only.");
String yesNo = input.nextLine();
if(yesNo.equals("yes"))
theMath();
else
System.out.println("Thanks for calculating with me! It certainly was fun!");
}while(redo.equals("yes"))
As for the other part of your question. If you have two int values and want to get a decimal from a division, you can do it like this:
int x = 2;
int y = 3;
double result = (double)x/y;
System.out.println(result);
This is called casting.
I have this short snippet of code where I have to check a string to see if it contains integers and possibly a decimal. The string is an amount of money (12.34) so as well it can not go past the fourth index.
My question is I'm being told to use charAt() (and in my code I used matches() and contains() which is wrong) to check for integers and decimals so that this routine will return a boolean that is true if the string works with those parameters, however I'm confused at how to go about converting this to use charAt() instead of matches() and contains().
As well, I'm sorry if I formatted this wrong, or worded something wrong, or the code looks awful, I'm in my first semester of Java and it's my very first programming class I've ever taken so I'm a bit rough.
import java.util.Scanner;
public class Auction
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
String price;
String quantity;
System.out.print("How much money are you willing to bet on this item?: $");
price = keyboard.next();
if(price.matches("[0-9]*") && price.length() <= 5)
{
Float f = Float.parseFloat(price);
System.out.printf("$%5.2f", f);
System.out.println();
}
else if(price.matches("[0-9]*") && price.length() <= 5 && price.contains("."))
{
Float f = Float.parseFloat(price);
System.out.printf("$%5.2f", f);
System.out.println();
}
else
{
System.out.println("Invalid input");
}
System.out.print("What quantity do you want to bid on?: ");
quantity = keyboard.next();
if(quantity.contains("."))
{
System.out.println("Invalid input");
}
}
}
I am typing this from a phone. So excuse the mistakes please. have u been asked by your professor to use charAt instead of regex and matches?
if (inpString!= null && !inpString.isEmpty () && inpString.length() <= 5){
int periodCount = 0;
for (int i=0; i < inpString.length (); i++){
char c = inpString.charAt (i);
if (c == '.'){
periodCount++;
}else if (c >= '0' && c <= '9'){
}else {
System.out.println("invalid output");
break;
}
if(periodCount > 1){
System.out.println("too may periods. Invalid output");
break;
}
}
}else {
System.out.println ("invalid input");
}
Can you comment if u need to check that there are no thousandth digit i.e 1.234? If yes make sure
inpString.substring
(inpString.lastIndexOf
(".")).length < 3
with all the null and indexOutOfBounds checks
How about this way?
import java.util.Scanner;
public class Auction {
private static final String numberRegex = "^\\d*(\\.\\d+)?$";
private static final String integerNumber = "^\\d*$";
private static final int MAX_LENGTH = 5;
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String price;
String quantity;
System.out.print("How much money are you willing to bet on this item?: $");
price = keyboard.next();
if (price.length() <= MAX_LENGTH && price.matches(numberRegex)) {
Float f = Float.parseFloat(price);
System.out.printf("$%5.2f\n", f);
} else {
System.out.println("Invalid input");
return;
}
System.out.print("What quantity do you want to bid on?: ");
quantity = keyboard.next();
if (!quantity.matches(integerNumber)) {
System.out.println("Invalid input");
}
}
}
My code is running fine, but every line where I use a scanner it warns me that there is a "Resource leak; 'userGuess' is never closed" I don't understand what it means and could use some help solving it. Also if there is anything else in my code worth fixing I could use the help. Be warned I have a limited knowledge of Java programming. I also cannot get my TryCounter++ to work...
package masterMind2_1;
import java.util.Scanner;
public class MasterMind2_1 {
public static void main(String[] args) {
System.out.println("This is MasterMind, a logic game");
System.out.println("To win you must guess correctly where each number is(The Numbers Range from 1-4)");
System.out.println("You will be told if you get one correct");
System.out.println("You will only get 10 tries, then you lose");
System.out.println("Lets begin");
//Declare Array
int [] answerArray;
answerArray= new int [4];
//Initialize Array
//Change these value to change the answers needed to win
answerArray[0]=2;
answerArray[1]=3;
answerArray[2]=2;
answerArray[3]=2;
// //Create Board
// System.out.println("-- -- -- --");
boolean guessedAll = false;
int guessedCount=0;
int tryCounter=0;
while(tryCounter<9 || !guessedAll){
System.out.println("What is the first Number?");
Scanner userGuess = new Scanner(System.in);
int num = userGuess.nextInt();
if (num==answerArray[0]) {
guessedCount++;
}
System.out.println("What is the Second Number?");
Scanner userGuess1 = new Scanner(System.in);
int num1 = userGuess1.nextInt();
if (num1==answerArray[1]) {
guessedCount++;
}
System.out.println("What is the Third Number?");
Scanner userGuess2 = new Scanner(System.in);
int num2 = userGuess2.nextInt();
if (num2==answerArray[2]) {
guessedCount++;
}
System.out.println("What is the Fourth Number?");
Scanner userGuess3 = new Scanner(System.in);
int num3 = userGuess3.nextInt();
if (num3==answerArray[3]) {
guessedCount++;
}
System.out.println("Your guess was "+ num+" "+num1+" "+num2+" "+num3);
if (num==answerArray[0]) {
System.out.println("First number was correct");
} else {
System.out.println("First number was incorrect");
}
if (num1==answerArray[1]) {
System.out.println("Second number was correct");
} else {
System.out.println("Second number was incorrect");
}
if (num2==answerArray[2]) {
System.out.println("Third number was correct");
} else {
System.out.println("Third number was incorrect");
}
if (num3==answerArray[3]) {
System.out.println("Fourth number was correct");
} else {
System.out.println("Fourth number was incorrect");
}
if (guessedCount==4) {
System.out.println("YAY you won!!");
guessedAll=true;
tryCounter=10;
} else {
System.out.println("Try again, except this time don't fail!");
guessedAll=false;
tryCounter++;
guessedCount=0;
}
}//What if I collected all of the values first
} //then told them if they were right or Wrong?
//Black and White Pegs?
//Fix TryCounter...Why isn't it working
}
Thank you for the Help!
The error message is telling you that you never call the close() method on your Scanner object. A worse problem is that you create multiple Scanners when you only need one.
As for tryCounter not working...
while(tryCounter<9 || !guessedAll)
This will keep looping if either part of the condition is true. My guess is that !guessedAll is evaluating to true beyond 9 guesses, so your loop keeps running. You'll need to change the || to an && to get it stop looping after 9 tries. (Also, print out the values of your variables or use a debugger so you can verify that they are changing when you expect them to.)
Im looking to make this loop after it asks them a question in this case ""What is 2+2?" then taking there input, Then the program should ask "Are you sure Y/N" if they awnser no i want it to go back to the start of this loop and allow them to redo the question. As it is i can't get this to loop and after this part works i will need to do 9 more questions in the same format
import java.util.Scanner;
class Quiz
{
public static void main (String[] args)
{
int q1=0 , q2=0;
boolean correct = false;
char yn1='y';
String q3 , q4;
Scanner input1 = new Scanner( System.in );
int count = 0 ;
//Question 1 start
while (correct == false)
{
System.out.println("What is 2+2? ");
System.out.println("Choices: 0,2,4,8");
q1 = input1.nextInt(); //used after loop
System.out.println("Are You Sure? (y/n)");
char c = input1.next().charAt(0); // Changed LINE
if (c=='y') // Changed LINE
{
if ( q1 == 4) //q1 was stated during loop
System.out.println("You were correct 2+2 = 4");
else
System.out.println("You were wrong");
break;
}
}
//Question 2 start
while (correct == false)
{
System.out.println("how many legs does a legless cow have?");
System.out.println("Choices: 0,25,4,31");
q2 = input1.nextInt();
System.out.println("Are You Sure? (y/n)");
char c = input1.next().charAt(0);
if (c=='y')
{
if ( q2 == 0)
System.out.println("You were correct, the cow has 0 legs");
else
System.out.println("You were wrong");
break;
}
}
//Question 3 start
while (correct == false)
{
System.out.println("What is the capital city of Canada?");
System.out.println("Choices: Toronto, Montreal, Vancouver, Ottawa (capitals count)");
q3 = input1.nextLine();
System.out.println("Are You Sure? (y/n)");
char c = input1.next().charAt(0);
if (c=='y')
{
if ( "Ottawa".equals(q3))
System.out.println("You were correct, The capital is Ottawa");
else
System.out.println("You were wrong");
break;
}
}
}
}
A new problem has occurred i have used the one helpful example and may try to change it to an array later but not in till i get the basics working. all the Questions usings int work so far Ie.
//Question 1 start
while (correct == false)
{
System.out.println("What is 2+2? ");
System.out.println("Choices: 0,2,4,8");
q1 = input1.nextInt(); //used after loop
System.out.println("Are You Sure? (y/n)");
char c = input1.next().charAt(0); // Changed LINE
if (c=='y') // Changed LINE
{
if ( q1 == 4) //q1 was stated during loop
System.out.println("You were correct 2+2 = 4");
else
System.out.println("You were wrong");
break;
}
}
But now i want to use a word awnser so i made a string and put it in instead of int but now instead of allowing input for q3 it skips to input of y/n i don't understand why all of a sudden it would do this yet the other questions work correctly with int.
while (correct == false)
{
System.out.println("What is the capital city of Canada?");
System.out.println("Choices: Toronto, Montreal, Vancouver, Ottawa (capitals count)");
String q3 = input1.nextLine();
System.out.println("Are You Sure? (y/n)");
char c = input1.next().charAt(0);
if (c=='y')
{
if ( "Ottawa".equals(q3))
System.out.println("You were correct, The capital is Ottawa");
else
System.out.println("You were wrong");
break;
}
}
Im sorry if this hasn't been enough detail or is formated wrong and will be sure to fix it if it is.
When reading input, always use q1 = Integer.parseInt(input1.nextLine()); (Even better, use the BufferedReader class). That way, your reading will work smoothly.
Secondly, you can place the if (q1 == 4) within the if (yn1.equals("Y")) statement. If the user has typed "Y" then set correct = true; to proceed to the next question. Further, if the user's answer is correct then increment the counter of right answers else print wrong. So the loop looks like this:
while (correct == false) {
System.out.println("What is 2+2? ");
System.out.println("Choices: 0,2,4,8");
q1 = Integer.parseInt(input1.nextLine());
System.out.println("Are You Sure? (Y/N)");
yn1 = input1.nextLine();
if (yn1.equals("Y")) {
correct = true;
if (q1 == 4) {
System.out.println("You were correct 2+2 = 4");
count++;
} else
System.out.println("You were wrong");
}
}
A few things to look into:
You print "Choices: 0,2,4,8", but nothing stops the user to enter 3 or 3000. Is the choices statement necessary? Then you'll need to check if the user has entered within that range or not also.
Instead of copying & pasting this same loop n times, make use an an array. Have all questions & answers stored in some String array for now. Something like this:
for (int i = 0; i < questions.length; i++) {
boolean nextQ = false;
while (nextQ == false) {
System.out.println(questions[i]);
String ans = input1.nextLine();
System.out.println("Are You Sure? (Y/N)");
yn = input1.nextLine();
if (yn.equalsIgnoreCase("Y")) {
nextQ = true;
if (ans.equals(answers[i])) {
System.out.println("You were correct " + questions[i]
+ " = " + answers[i]);
count++;
} else
System.out.println("You were wrong");
}
}
}
I changed the boolean variable correct to nextQ to avoid confusion. Hope the sets you in the right direction.
I tried to compile your program.But I am getting some errors:-
error: variable q1 might not have been initialized
According to what I understand from ur question.Here is the program u want:-
import java.util.Scanner;
class stack1
{
public static void main (String[] args)
{
int q1=0 , q2 , q3, q4, q5, q6 , q7 ,q8 ,q9 ,q10 , a ;
boolean correct = false;
char yn1='Y';
Scanner input1 = new Scanner( System.in );
int count = 0 ;
while (correct == false)
{
System.out.println("What is 2+2? ");
System.out.println("Choices: 0,2,4,8");
q1 = input1.nextInt(); //used after loop
System.out.println("Are You Sure? (Y/N)");
char c = input1.next().charAt(0); // Changed LINE
if (c=='y') // Changed LINE
{
System.out.println("Exiting the program");
correct = true; //It should now stop the loop and carry on
break;
}
}
if ( q1 == 4) //q1 was stated during loop
System.out.println("You were correct 2+2 = 4");
else
System.out.println("You were wrong");
//Soon will add int score and add 1 each time its correct
// will be using 9 more loops the exact same way
}
}
I have mentioned all the changed lines with comment '//changed line' .
This is the answer for the edited Question:-
import java.util.Scanner;
class stack2
{
public static void main (String[] args)
{
int q1=0 , q2 , q3, q4, q5, q6 , q7 ,q8 ,q9 ,q10 , a ;
boolean correct = false;
char yn1='Y';
String s="";
System.out.println(s);
Scanner input1 = new Scanner( System.in );
int count = 0 ;
while (correct == false)
{
System.out.println("What is the capital city of Canada?");
System.out.println("Choices: Toronto, Montreal, Vancouver, Ottawa (capitals count)");
s = input1.nextLine();
System.out.println(s);
System.out.println("Are You Sure? (Y/N)");
char c = input1.next().charAt(0); // Changed LINE
if (c=='y') // Changed LINE
{
System.out.println("Exiting the program");
correct = true; //It should now stop the loop and carry on
break;
}
if (s.equals("Ottawa")) //q1 was stated during loop
System.out.println("You were correct, The capital is Ottawa");
else
System.out.println("You were wrong");
}
//Soon will add int score and add 1 each time its correct
// will be using 9 more loops the exact same way
}
}
Be careful while entering the input.It shoul be exactly "Ottawa". Best of luck