New Java developer - Simple Q - java

I have just recently started coding and am quite the beginner. I'm trying to make a program that simply asks the user to enter a "password", and depending on whether the password is correct; increment a counter. And, once the counter reaches 10, print out a message.
Basically what I'm trying to make is like a "clip-card", like one of those you can get at a coffee shop (you get every 10th coffee free).
So, this is what I have now. I just need to know how to make the program continue after inputting a password, and keep track of the inputs.
Ohhh and... If this is unclear, please say so and I will try to clarify.
This is what I have to far...
import java.util.Scanner;
public class Coffee {
public static void main(String [] args){
int count = 0;
String pass = "hey";
System.out.println("Enter password: ");
Scanner key = new Scanner(System.in);
String moves = key.nextLine();
if(moves.compareTo(pass) == 0){
count++;
System.out.println("You're one step closer to a free coffe! You have so far bought " + count + " coffe(s)");
}
if(count % 10 == 0 && count != 0){
System.out.println("You've got a free coffe!");
}
if(moves.compareTo(pass) != 0){
System.out.println("Wrong password! Try again.\n");
}
}
}

When would your program end? The way you describe it, it could just go on forever.
If that is the case, you just enclose it in a while loop :
public static void main(String [] args) {
Scanner key;
String moves;
int count = 0;
String pass = "hey";
while(true) {
System.out.println("Enter password: ");
key = new Scanner(System.in);
moves = key.nextLine();
if(moves.compareTo(pass) == 0){
count++;
System.out.println("You're one step closer to a free coffe! You have so far bought " + count + " coffe(s)");
}
if(count % 10 == 0 && count != 0){
System.out.println("You've got a free coffe!");
}
if(moves.compareTo(pass) != 0){
System.out.println("Wrong password! Try again.\n");
}
}
}
But you really should have an breaking condition.

You need loop(while,do-while,or for loop) to do this kind of repeated stuff .
Sample code may help
import java.util.Scanner;
public class Coffee {
public static void main(String[] args) {
int count = 0;
String pass = "hey";
System.out.println("Enter password: ");
Scanner key = new Scanner(System.in);
String moves = key.nextLine();
boolean flag = true;
while (flag) {
if (moves.compareTo(pass) == 0) {
count++;
System.out
.println("You're one step closer to a free coffe! You have so far bought "
+ count + " coffe(s)");
}
if (count == 10 && count != 0) {
System.out.println("You've got a free coffe!");
count=0;
}
if (moves.compareTo(pass) != 0) {
System.out.println("Wrong password! Try again.\n");
}
System.out.println("Do you want to continue ..(y/n)");
String choice = key.nextLine();
if (choice.equals("n")) {
flag = false;
} else {
flag = true;
}
}
}
}

I will give you a while and do-while loop to chose from
While loop
Scanner key;
String moves;
int count = 0;
String pass = "hey";
boolean condition=true;
while(condition) {
System.out.println("Enter password: ");
key = new Scanner(System.in);
moves = key.nextLine();
if(moves.compareTo(pass) == 0){
count++;
System.out.println("You're one step closer to a free coffe! You have so far bought " + count + " coffe(s)");
if(count % 10 == 0 && count != 0){
System.out.println("You've got a free coffe!");
condition=false;
}
}
else if(moves.compareTo(pass) != 0){
System.out.println("Wrong password! Try again.\n");
}
}
Do-While loop
Scanner key;
String moves;
int count = 0;
String pass = "hey";
boolean condition=true;
do{
System.out.println("Enter password: ");
key = new Scanner(System.in);
moves = key.nextLine();
if(moves.compareTo(pass) == 0){
count++;
System.out.println("You're one step closer to a free coffe! You have so far bought " + count + " coffe(s)");
if(count % 10 == 0 && count != 0){
System.out.println("You've got a free coffe!");
condition=false;
}
}
else if(moves.compareTo(pass) != 0){
System.out.println("Wrong password! Try again.\n");
}
}while(condition);

Related

Best way to code my unintelligent Nim game?

This is my nim game (goal is dont be the last person to pick up marbles), can someone please guide me. In playing the game, I have just one question
How can I keep track of whose turn it is, I guess if I can keep track of that I can monitor my remainingMarbles. This is the crux of my code. Please help
public class Nim{
public static void main(String[] args)
{
System.out.println("************** Welcome to the game of Nim *******************");
System.out.println("The object of this game is to make me take the last marble off the table");
System.out.println("You must take at least 1 and you can take up to 3 marbles on your turn");
System.out.println("You can go first");
Scanner scan = new Scanner(System.in);
final int MARBLES = 13;
int remainingMarbles;
String input;
do {
//boolean whoseTurn = true;
remainingMarbles = MARBLES;
System.out.println("There are " + MARBLES + " marbles on the table");
while (remainingMarbles > 0){
remainingMarbles -= getUserSelection();
System.out.println("There are " + (remainingMarbles -= getComputerSelection()) + " marble(s) on the table.");
}
if (1 <= remainingMarbles && remainingMarbles <= 2 && remainingMarbles < 0) {
System.out.println("Congratulations! you won!");
System.out.println("Want to play again? y/n");
input = scan.nextLine();
input = input.toLowerCase();
} else
System.out.println("Hard luck you lose!");
System.out.println("Want to play again? y/n");
input = scan.nextLine();
input = input.toLowerCase();
}while (input.charAt(0) == 'y');
}
private static int getUserSelection()
{
Scanner scan = new Scanner(System.in);
do {
System.out.println("Enter 1, 2 or 3");
int userSelection = scan.nextInt();
if (isValidMove(userSelection)){
return userSelection;
}
else {
System.out.println("Not a valid entry");
}
}while (true);
}
private static boolean isValidMove(int input)
{
return 1 <= input && input <= 3;
}
private static int getComputerSelection ()
{
Random generator = new Random();
int computerSelection = 1 + generator.nextInt(3);
System.out.println("The computer chooses " + computerSelection);
return computerSelection;
}
}
First, make a boolean before the loop.
boolean whoseTurn = true;
When the variable is true it's the first player's turn, otherwise the second player's turn.
Now inside the while loop we change the variable at the end of every repetition:
whoseTurn = !whoseTurn;
(Which is a faster way of this)
if(whoseTurn) whoseTurn = false;
else whoseTurn = true;
To conclude, you should do something like that:
...
boolean whoseTurn = true;
while(remainingMarbles > 0){
remainingMarbles -= getUserSelection();
System.out.println("There are " + (remainingMarbles -= getComputerSelection()) + " marble(s) on the table.");
whoseTurn = !whoseTurn;
}
...

How to generate a random number after user guess the correct number?

I have written the code below. I have run the program and it allows the user to guess the correct number and return the message successfully. However, I couldn't get it to regenerate a new random number? I also couldn't include an option to ask whether the user wants to quit or not. Please help. Thank you.
import java.util.*;
class CompterAge {
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
boolean correctGuess = false;
Random r = new Random();
int randNum = r.nextInt(100-1+1) + 1;
while (!correctGuess) {
System.out.println("Guess the computer's age: ");
int guess = sc.nextInt();
if ((guess > 0) && (guess <= 100)) {
if (guess > randNum) {
System.out.println("Your guess is bigger than the number. You should go lower.");
correctGuess = false;
} else if (guess < randNum) {
System.out.println("Your guess is smaller than the number. You should go higher.");
correctGuess = false;
} else {
System.out.println("Congratulations. You got the number! The number is " + randNum);
System.out.println("Do you wish to continue the game? Yes/No");
String input = sc.next();
if (input == "Yes") {
correctGuess = false;
} else {
break;
}
}
} else {
System.out.println("Please enter a number between 1 to 100.");
correctGuess = false;
}
}
}
}
This code works, I have added another flag variable and corrected some logical errors. See the comments.
boolean correctGuess = false;
boolean endGame = false;
Random r = new Random();
while (!endGame){
int randNum = r.nextInt(101); //Why did you have (100-1+1) + 1 ?? Simple (101) was enough
correctGuess = false;
while (!correctGuess) {
System.out.println("Guess the computer's age: ");
int guess = sc.nextInt();
if ((guess > 0) && (guess <= 100)) {
if (guess > randNum) {
System.out.println("Your guess is bigger than the number. You should go lower.");
correctGuess = false;
} else if (guess < randNum) {
System.out.println("Your guess is smaller than the number. You should go higher.");
correctGuess = false;
} else {
correctGuess = true; //Will exit the Inner Loop
System.out.println("Congratulations. You got the number! The number is " + randNum);
System.out.println("Do you wish to continue the game? Yes/No");
String input = sc.next().toLowerCase();
if (input.equals("yes")) { //You can not use == for String Comparisons
endGame = false;
} else {
endGame = true;
}
}
} else {
System.out.println("Please enter a number between 1 to 100.");
correctGuess = false;
}
}
}
Your random number generation is done outside of your while loop so when they input that they want to continue the game it should then generate a new number:
System.out.println("Congratulations. You got the number! The number is " + randNum);
System.out.println("Do you wish to continue the game? Yes/No");
String input = sc.next();
if (input.equals("Yes")) {
randNum = r.nextInt(100-1+1) + 1;
correctGuess = false;
} else {
break;
}

How do I include a question asking the user if they want to play again?

I am still new to Java and as such I am still figuring some things out. I have been having issues with including code asking the user if they want to play again. I have attempted putting it in the main class in a print statement which gave me an error. After that, I attempted putting it in the Guess.java class in multpile places but I just recieved errors. I have read up on the issue and some sites have suggested a while loop but I am unsure how to implement it into my current code. I have included both the main class which is called GuessingGame.java and the Guess.java class below. Thank you for any assistance that can be provided.
GuessingGame.java
public class GuessingGame {
public static void main(String[] args) {
new Guess().doGuess();
}
}
Guess.java
class Guess {
private int answer = 0;
int tries = 0;
Scanner input = new Scanner(System.in);
int guess, i;
boolean win = false;
int amount = 10;
public Guess() {
answer = generateRandomNumber();
}
//Generate a private number between 1 and a thousand
private int generateRandomNumber() {
Random rand = new Random();
return rand.nextInt(1000) + 1;
}
public void doGuess() {
while (!win) {
System.out.println("You are limited to ten attempts."
+ " Guess a number between 1 and 1000: ");
guess = input.nextInt();
if (tries > 9) {
System.out.println("You should be able to do better!"
+ " You have hit your ten guess limit. The number"
+ " was: " + answer);
System.out.println("Do you want to play again?: ");
return;
}
if (guess > 1000) {
System.out.println("Your guess is out of the range!");
} else if (guess < 1) {
System.out.println("Your guess is out of the range!");
} else if (guess == answer) {
win = true;
tries++;
} else if (guess < answer && i != amount - 1) {
System.out.println("Your guess is too low!");
tries++;
} else if (guess > answer && i != amount - 1) {
System.out.println("Your guess is too high!");
tries++;
}
}
System.out.println("Congragulations! You guessed the number!"
+ "The number was: " + answer);
System.out.println("It took you " + tries + " tries");
}
}
You already found a good position for adding this functionality:
System.out.println("Do you want to play again?: ");
The first step now is to also tell the user what he/she should enter after that question:
System.out.println("Do you want to play again? (enter 0 for yes and 1 for no): ");
After that we need to get the user input of course:
int number;
//If the user enters e.g. a string instead of a number, the InputMismatchException
//will be thrown and the catch-block will be executed
try {
number = input.nextInt();
//If number < 0 OR number > 1
if(number < 0 || number > 1) {
//The rest of the try-block will not be executed.
//Instead, the following catch-block will be executed.
throw new InputMismatchException();
}
break;
}
catch(InputMismatchException e) {
System.out.println("Enter 0=yes or 1=no");
//Clears the scanner to wait for the next number
//This is needed if the user enters a string instead of a number
input.nextLine();
}
If you don't know about try-catch-statements yet, I suggest to read this explanation. For details about the InputMismatchException, please see the documentation.
The problem now is that the user only has one chance to enter 0 or 1. If the user makes a wrong input the program will just stop. One solution to this problem is to just put the code in a while-loop:
int number;
while(true) {
try {
number = input.nextInt();
if(number < 0 || number > 1) {
throw new InputMismatchException();
}
break;
}
catch(InputMismatchException e) {
System.out.println("Enter 0=yes or 1=no");
input.nextLine();
}
}
After this block, we can be sure that number is either 0 or 1. So now we can add a simple if-statement to check the value:
if(number == 0) {
new Guess().doGuess();
}
return;
So all in all the code looks like this:
System.out.println("Do you want to play again? (enter 0 for yes and 1 for no): ");
int number;
while(true) {
try {
number = input.nextInt();
if(number < 0 || number > 1) {
throw new InputMismatchException();
}
break;
}
catch(InputMismatchException e) {
System.out.println("Enter 0=yes or 1=no");
input.nextLine();
}
}
if(number == 0) {
new Guess().doGuess();
}
return;
Don't forget to add the following import-statements:
import java.util.Scanner;
import java.util.InputMismatchException;
import java.util.Random;
Try this. Basically, if the user responds with "yes" , we will call the function again.
if (tries > 9) {
System.out.println("You should be able to do better!"
+ " You have hit your ten guess limit. The number" + " was: " + answer);
System.out.println("Do you want to play again? (yes/no): "); // modified line
if("yes".equalsIgnoreCase(input.next())){ // newly added if block
answer = generateRandomNumber();
tries=0;
i=0;
win = false;
doGuess();
}
return;
}

How do I get the break command to go back to my for each loop

I know I asked a similar question like this earlier (I figured it out though)
*while(!newWord.equalsIgnoreCase(guess))
forloop:
{ while(!newWord.equalsIgnoreCase(guess))
for ( String a : spaces.split("\\s"))
{
count++;
int x = Integer.valueOf(a);
if (x > guess.length())
{
System.out.println("Your input is not valid, try again");
break innerloop;
}
if (Character.toLowerCase(newWord.charAt(x)) == letterInput.charAt(0))
{
//System.out.println("Guess is correct for position " + x);
guess = guess.substring(0, x) + letterInput + guess.substring(x + 1, guess.length());
}
if (Character.toLowerCase(newWord.charAt(x)) != letterInput.charAt(0))
{
if(count < spaces.split("\\s").length - 1)
{
break forloop;
}
}
if (count == spaces.split("\\s").length)
guesses= guesses - 1;
System.out.println("Your letter was not found in spaces you provided");
System.out.println("Guesses Remaining: " + guesses);
break;
}*
but now the break command that I have at the third if statement after the for loop just takes me back to the loop towards the beginning of my whole code
*while(!newWord.equalsIgnoreCase(guess))
innerloop:
{ while(true)
{
System.out.println("Please enter the letter you want to guess");
String letterInput = keyboard.next();
letterInput = Character.toString(letterInput.charAt(0));
if(!Character.isLetter(letterInput.charAt(0)))
{
System.out.println("Your input is not valid, try again");
break;
}
if(letterInput.equalsIgnoreCase("solve"))
{
System.out.println("Please solve the answer:");
String userSolve = keyboard.next();
if (!userSolve.equalsIgnoreCase(newWord))
{
System.out.println("That is not the secret word");
guesses = guesses - 1;
System.out.println("Guesses remaining: " + guesses);
}
else
{
System.out.println("You win!");
System.out.println("You have guessed the word! Congratulations");
System.out.println("Would you like to play again? Yes(y) or No (n)");
response = keyboard.next();
if (response.equalsIgnoreCase("n"))
{
System.exit(0);
}
if(response.equalsIgnoreCase("y"))
{
continue;
}
As you can see I placed labels on the loops I specifically want to go back to. My break is currently taking me back to my innerloop label BUT I want it to take me back to my forloop label. How exactly do I do that? I tried wrapping the for loop with while loops because thats what worked for me last time but it is not working here. Here is my whole code for reference, I apologize if its hard to read I've only started coding 2 months ago.
package e;
import java.util.Scanner;
public class HangmanBeta{
private static final boolean testingMode = true;
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
keyboard.useDelimiter("\\n");
while (true) {
System.out.println("Enter your difficulty: Easy (e), Intermediate (i), or Hard (h)");
String diff = keyboard.next();
int amountOfSpaces = 0;
String response = "";
String guess = "";
String newGuess = "";
String s = "";
int count = 0;
String newWord = "loops";//RandomWord.newWord();
int guesses = 0;
for (int i = 0; i < newWord.length(); i++) {
guess = newWord.replaceAll("[^#]", "-");
}
if ((diff.equalsIgnoreCase("e")) || (diff.equalsIgnoreCase("i")) || (diff.equalsIgnoreCase("h"))) {
if (diff.equalsIgnoreCase("e"))
{
guesses = 15;
}
if(diff.equalsIgnoreCase("i"))
{
guesses = 12;
}
if(diff.equalsIgnoreCase("h"))
{
guesses = 15;
}
if (testingMode == true)
{
System.out.println("The secret word is:" + " " + newWord);
}
System.out.println("The word is:" + " " + guess);
while(!newWord.equalsIgnoreCase(guess))
innerloop:
{ while(true)
{
System.out.println("Please enter the letter you want to guess");
String letterInput = keyboard.next();
letterInput = Character.toString(letterInput.charAt(0));
if(!Character.isLetter(letterInput.charAt(0)))
{
System.out.println("Your input is not valid, try again");
break;
}
if(letterInput.equalsIgnoreCase("solve"))
{
System.out.println("Please solve the answer:");
String userSolve = keyboard.next();
if (!userSolve.equalsIgnoreCase(newWord))
{
System.out.println("That is not the secret word");
guesses = guesses - 1;
System.out.println("Guesses remaining: " + guesses);
}
else
{
System.out.println("You win!");
System.out.println("You have guessed the word! Congratulations");
System.out.println("Would you like to play again? Yes(y) or No (n)");
response = keyboard.next();
if (response.equalsIgnoreCase("n"))
{
System.exit(0);
}
if(response.equalsIgnoreCase("y"))
{
continue;
}
}
}
System.out.println("Please enter the spaces you want to check (seperated by spaces)");
String spaces = keyboard.next();
amountOfSpaces = spaces.length();
if (diff.equalsIgnoreCase("e"))
{
if(amountOfSpaces != 7)
{
System.out.println("Your input is not valid, try again");
break innerloop;
}
}
if (diff.equalsIgnoreCase("i"))
{
if(amountOfSpaces != 5)
{
System.out.println("Your input is not valid, try again");
break innerloop;
}
}
if (diff.equalsIgnoreCase("h"))
{
if(amountOfSpaces != 3)
{
System.out.println("Your input is not valid, try again");
break innerloop;
}
{
while(!newWord.equalsIgnoreCase(guess))
forloop:
{ while(!newWord.equalsIgnoreCase(guess))
for ( String a : spaces.split("\\s"))
{
count++;
int x = Integer.valueOf(a);
if (x > guess.length())
{
System.out.println("Your input is not valid, try again");
break innerloop;
}
if (Character.toLowerCase(newWord.charAt(x)) == letterInput.charAt(0))
{
//System.out.println("Guess is correct for position " + x);
guess = guess.substring(0, x) + letterInput + guess.substring(x + 1, guess.length());
}
if (Character.toLowerCase(newWord.charAt(x)) != letterInput.charAt(0))
{
if(count < spaces.split("\\s").length - 1)
{
break forloop;
}
if (count == spaces.split("\\s").length)
guesses= guesses - 1;
System.out.println("Your letter was not found in spaces you provided");
System.out.println("Guesses Remaining: " + guesses);
break;
}
if (guesses == 0)
{
System.out.println("You have failed to guess the word....:(");
System.out.print("Would you like to play again? Yes(y) or No(n)");
response = keyboard.next();
if (response.equalsIgnoreCase("n"))
{
System.exit(0);
}
if(response.equalsIgnoreCase("y"))
{
continue;
}
} }
if (newWord.equalsIgnoreCase(guess))
{
System.out.println("You win!");
System.out.println("You have guessed the word! Congratulations");
System.out.println("Would you like to play again? Yes(y) or No (n)");
response = keyboard.next();
if (response.equalsIgnoreCase("n"))
{
System.exit(0);
}
if (response.equalsIgnoreCase("y"))
{
continue;
}
}
}
System.out.println("Your Guess is in the word");
}
if(guesses == guesses - 1)
{
System.out.println("Your letter was not found in spaces you provided");
System.out.println("Guesses Remaining: " + guesses);
break innerloop;
//System.out.print(spaces.split("\\s").length);
//System.out.println("Your Guess is in the word");
//System.out.println();
//System.out.println("Updated word " + guess);
//System.out.println("Guesses Remaining: " + guesses);
}
}
}
}
}
}
}
}
... but now the break command that I have at the third if statement after the for loop just takes me back to the loop towards the beginning of my whole code.
Actually, no.
A break never takes you back. It always takes you forward. In this case it takes you forward to immediately after the block with the label that you broke. For example:
while (....) {
label: while (...) {
...
if (...) break label;
...
}
// Breaks to HERE
}
You may then go back because of something in the context you went to. But it is the context that does it, not the break.
Unfortunately, I can't figure out how to apply this to your example because 1) you don't explain what the code is supposed to do, 2) it is hard to figure out which of the versions you refer to, 3) the code is not compilable, and 4) the readability issues make my head hurt.
So unless you can figure out how to make your code more readable, that is all the help I can give you.

Having issues with having a program re-run

I am writing a program that will ask the user to guess a random number 6 times. The program has to ask if they want to play again and will keep a running total of the wins/losses.
How would I have the program rerun?
heres the code:
import java.util.Scanner;
import java.util.Random;
public class Project {
public static void main(String[] args) {
String input;
double guess = 0;
int number;
double wins = 0;
double losses = 0;
String repeat;
Scanner keyboard = new Scanner(System.in);
Random randomNumbers = new Random();
System.out.println("Welcome to Higher/Lower!");
System.out.println("Enter your name: ");
input = keyboard.nextLine();
while(input.equalsIgnoreCase("yes")); {
number = randomNumbers.nextInt(100) + 1;
System.out.println("I've chosen my number, " + input + "You only have 6 tries, good luck!"); }
for(int num = 1; number != guess && number <= 6; num++) {
System.out.println("Enter guess " + num + ":");
guess = keyboard.nextDouble();
if(guess < number)
System.out.println("higher.");
else if(guess > number)
System.out.println("lower.");
else
System.out.println("Congratulations!"); }
if(guess == number) {
System.out.println("You guesses my number!"); wins++; }
if(guess != number) {
System.out.println("Sorry, " + input + " my number was " + number +
"You lose!"); losses++; }
System.out.println("Do you want to play again? (Yes/No): ");
repeat = keyboard.nextLine();
if(input.equalsIgnoreCase("no")); {
System.out.println("Thanks for playing!"); }
System.out.println(wins + " wins");
System.out.println(losses + " losses");
}
}
It is skipping over asking me if i want to play again or not and i dont know what kind of loop to use
Wihtout your code, I'm assuming this is what you need.
boolean doContinue = true;
do {
//guess random number 6 times
//do you want to continue?
// yes -> doContinue = true;
// no -> doContinue = false;
} while (doContinue );
I would suggest making your loop a do-while loop like this:
do {
for (int i=0; i<6; i++){
/*
insert code for the guessing/checking/etc.
*/
}
System.out.print("Would you like to continue? [Y/n] ");
} while (scan.next().toUpperCase().charAt(0) != 'Y');

Categories

Resources