Java Loop only running once - java

Im building a code guessing game if you insert an invalid input ie( 333 ) it will prompt you to change your guess. however this only works on guess #1 on guess #2 - #6 it will let any invalid input go through
public void game(){
System.out.println("Enter guess #" + (guessAtt + 1));
guess = keyboard.next();
guess = guess.toLowerCase();
if( guess.equals(quit)){
System.exit(0);
}
if (guess.length() < 2){
System.out.println("Guess Too short try again");
game();
}
if (guess.length() > 3){
System.out.println("Guess too long try again");
game();
}
letter1 = guess.charAt(0);
letter2 = guess.charAt(1);
letter3 = guess.charAt(2);
isValid();
}
public boolean isValid(){
if (letter1.equals('a')|| letter1.equals('b')|| letter1.equals('c')|| letter1.equals('d')|| letter1.equals('e')){
isValid1 = true;
}
if(letter2.equals('a')|| letter2.equals('b')|| letter2.equals('c')|| letter2.equals('d')|| letter2.equals('e')){
isValid2 = true;
}
if(letter3.equals('a')|| letter3.equals('b')|| letter3.equals('c')|| letter3.equals('d')|| letter3.equals('e')){
isValid3 = true;
}
if(isValid1 == true && isValid2 == true && isValid3 == true){
isValid = true;
}
else {
isValid = false;
}
while (isValid == false){
System.out.println("invalid input try again\n");
game();
}
return isValid;
}

you could both use a while loop in the game that breaks when isValid() returns a true. You could also call the function game if isValid() returns a false value. Now you ask for a boolean value, but you don't use it. No matter what it returns, as long as your value contains the right lenght, the game ends.

Related

Compilation Error in a very silly program

import java.util.Scanner;
public class KekOrCringe {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String userGuess = "";
boolean Continue = true;
boolean ProperResponse = true;
boolean IsCorrect = true;
boolean YesNo = true;
while (Continue)
{
int secretAnswer = (int)(Math.random() * 2 + 1);
kekOrCringe(secretAnswer);
while (!IsCorrect)
{
System.out.println("Kek or Cringe?");
ProperResponse = false;
while (!ProperResponse) {
userGuess = scan.nextLine();
if (userGuess != "Kek")
System.out.println("Your entry is invalid, please try again!");
else if (userGuess != "Cringe")
System.out.println("Your entry is invalid, please try again!");
else
ProperResponse = true;
}
for (int guessCount = 0; guessCount < 1; guessCount++) {
if (userGuess = "Cringe" && userGuess != secretAnswer) {
System.out.println("It's KeK!");
guessCount++; }
else if (userGuess = "Kek" && userGuess != secretAnswer) {
System.out.println("It's CrInGe!");
guessCount++; }
else
System.out.println("Mr. Morgan, you got it right my boy!");
IsCorrect = true;
}
}
}
YesNo = false;
while(!YesNo) {
System.out.println("Would you like to play again? Yes/No");
String answer = scan.nextLine();
if (answer.equals("No")) {
Continue = false;
YesNo = true;
System.out.println("Fine. You were Cringe anyway!");
}
else if (answer.equals("Yes")) {
YesNo = true;
Continue = true;
IsCorrect = false;
}
}
}
public static String kekOrCringe(int secretAnswer) {
if (secretAnswer = 1) { return "Kek";}
if (secretAnswer = 2) { return "Cringe";}
}
}
Probably an overly complex way to do something unnecessary, but this is my first year in college learning to code, and I was asked to give this a try. I think it's funny, and will probably be funnier if it work, along with being good practice. I'm having trouble converting the int secretAnswer to a returned string, and then comparing the userGuess to the return type. Getting compilation errors on line 32 and 35. Any tips would be appreciated.
P.S. I realize it's silly. Trying to use this silly code as a learning opportunity.
Im guessing line 32 and 35 are the two ifs. userGuess != secretAnswer doesn't work since one is a String, the other an Integer. Your static method kekOrCringe(secretAnswer); returns the String you want, you just need to save it in a variable and then compare it to the userGuess.
Also please use lowercase variable names.
I can't add a comment so I am writing here.
userGuess is String but secretAnswer is int, and you are trying to check if they are equal (userGuess != secretAnswer).
You can use a new variable like secretGuess, assign kekOrCringe(secretAnswer) to secretGuess and check if userGuess is equal to secretGuess.
Like this:
String secretGuess = kekOrCringe(secretAnswer);
if (userGuess != secretGuess) {
//...
}
You are trying to compare int to string which is wrong
userGuess != secretAnswer
Also, instead of comparing you are assigning values inside if condition.
if (secretAnswer = 1) { return "Kek";}
if (secretAnswer = 2) { return "Cringe";}
It should be:
if (secretAnswer == 1) { return "Kek";}
if (secretAnswer == 2) { return "Cringe";}

How to go back into a while-loop, from an if statement?

Here's what i've been working on. I'm trying loop this while method, using booleans. (My teacher is incompetent, so i've been learning out of textbook.)
else { System.out.println("Do you want to restart? Y/N");
string answer = scn.next();
return;
if (scn.hasNext() && !no)) {
System.out.println("end");
} else{
continue;
}
/*if (repeat) {
continue;
} else {
System.out.println("End");
break;
}*/
}
This is nested in a while loop like so ....
import java.util.Scanner; import java.lang.String;
public class booleanvariables {
public static void main (String[] args){
Scanner scn = new Scanner(System.in);
int score1, score2;
String answer, e;
boolean bothHigh, atLeastOneHigh, atLeastOneModerate, noLow, tooLow, repeat;
while (true) {
System.out.print("Enter the first test score:\t");
score1 = scn.nextInt();
System.out.print("Enter the second test score:\t");
score2 = scn.nextInt();
answer = null;
e = "n";
bothHigh = (score1 >= 90 && score2 >= 90);
atLeastOneHigh = (score1 >= 90 || score2 >= 90);
atLeastOneModerate = (score1 >= 70 || score2 >= 70);
noLow = !(score1 < 50 || score2 < 50);
tooLow = (score1 <= 50 || score2 <= 50);
repeat = (answer == "yes" || answer == "y"); //|| answer == Y || answer == Yes);
if (tooLow)
System.out.println("Inputs are too low");
if (bothHigh)
System.out.println("Qualified to be a manager");
if (atLeastOneHigh)
System.out.println("Qualified to be a supervisor");
if (atLeastOneModerate && noLow)
System.out.println("Qualified to be a clerk");
/** NESTED WRONG I'M AWARE
*/
else { System.out.println("Do you want to restart? Y/N");
string answer = scn.next();
return;
if (scn.hasNext() && !no)) {
System.out.println("end");
} else{
continue;
}
/*if (repeat) {
continue;
} else {
System.out.println("End");
break;
}*/
}
}
}
}
This is much simpler than you think.
Just do it like this:
boolean stop = false;
while(!stop) {
//do whatever you want here
System.out.println("Do you want to quit?(yes or no");
String input = scan.nextLine();
if(input.equals("no")) {
stop = true;
}
}
That way, if you enter "no", it'll set the boolean to true, which then will make the condition for the while loop, !stop, equal to false.
answer == "yes"
You are checking if two objects are the same. You should use the equals method answer.equals("yes") || answer.equals("y")
Tested and Working to My Liking
I've reworked some branching. ( I use BlueJ as a compiler and it thinks this is an error without the input = scn.nextLine();
do {
//same booleans i've been using
if (!stop) {
System.out.print("Do you want to quit? (yes or no):\t");
//String input;
input = scn.nextLine();
}
//String input;
input = scn.next();
if(input.equals("yes")) {
stop = true;
System.out.println("Goodbye");
return;
}
} while (!stop);
I really don't know why blue J doesn't like it when initialize input from within the if statement

Java: Restarting program after achieving certain value

I'm making a game which allows the user to guess the random number. In the event the user guesses correctly, and he/she decides to play again, a new number must be generated. I assumed that if I set boolean value "restart" to "true" at both the beginning (while making it false soon thereafter), and then setting it back to true after "restart" became true again, then the program would start over...it did not. Do you see what I'm doing wrong? Thanks.
import java.util.*;
import javax.swing.*;
import java.util.Scanner;
public class RandomGuess2
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String userNum;
int userInput, numInt, genNum, amount = 0;
int repeatPlay = 0;
int x = 1;
boolean numTruth, restart;
boolean repeatIsYes = false;
restart = true;
userInput = JOptionPane.showConfirmDialog(null, "Would you like to try and guess the magic
number?", "Guessing Game", JOptionPane.YES_NO_OPTION);
genNum = (1 + (int)(Math.random() * 1000));
do
if((numTruth = (userInput == JOptionPane.YES_OPTION)) || (repeatIsYes = (userInput ==
JOptionPane.YES_OPTION)))
restart = false;
{
userNum = JOptionPane.showInputDialog(null,"Enter the number you're thinking between 1 &
1000: ");
numInt = Integer.parseInt(userNum);
if((numInt > 1000) || (numInt < 1)) {
JOptionPane.showMessageDialog(null, "Incorrect entry");
repeatIsYes = true;
}
else if(numInt > genNum) {
repeatIsYes = true;
repeatPlay = JOptionPane.showConfirmDialog(null, "You guessed too high!"
+ "\nWould you like to guess again?" + genNum);
}
else if(numInt < genNum) {
repeatIsYes = true;
repeatPlay = JOptionPane.showConfirmDialog(null, "You guessed too low!"
+ "\nWould you like to guess again?" + genNum);
}
else if(numInt == genNum) {
repeatIsYes = false;
repeatPlay = JOptionPane.showConfirmDialog(null, "How did you do that? You guessed
+ correctly!\nWould you like to guess again?" + genNum);
if(restart = (repeatPlay == JOptionPane.YES_OPTION))
{restart = true;}
}
if(repeatIsYes = (repeatPlay == JOptionPane.YES_OPTION)) {
numTruth = true;
repeatIsYes = true;
}
else {
numTruth = false;
repeatIsYes = false;
JOptionPane.showMessageDialog(null, "Goodbye! \nYou played " + amount + " times.");
break;
}
}
else {
numTruth = false;
repeatIsYes = false;
JOptionPane.showMessageDialog(null, "Goodbye!");
break;
}
while(numTruth = true);
}}
You never really use restart, i.e you only set it. To make your application start again check the value of restart at an appropriate place in your loop .
I don't have the time to thoroughly read your code (which, btw, is hard to read due to formatting and structure), but a simple solution would be to use two loops.
Here's some pseudocode:
while( playAnotherGame) { //this could be your "restart" flag
boolean gameIsRunning = true;
while( gameIsRunning ) {
//ask for user input
//check guesses
if( guessedCorrectly ) {
gameIsRunning = false; //game is finished
//display result
//ask for user input: restart or quit
if( quit ) {
playAnotherGame = false;
}
}
else {
//ask for user input: guess again, new game or quit
//handle user input
}
}
}
Btw, constructs like this are error prone and hard to read:
//you set and check repeatIsYes at the same time
if(repeatIsYes = (repeatPlay == JOptionPane.YES_OPTION)) {
numTruth = true;
repeatIsYes = true; //this is already true, see the if-condition
}

Java: Input comparison

I'm wondering why when I type 'y' after being asked if there are any more digits in this method the code works correctly and leaves the loop, but upon typing 'n' and hitting return, I need to type 'n' and hit return again or the process just hangs.
Why?
The string 'input' is being passed from the user's input in the main method and is in this case "addition".
private int add(String input)
{
int additionValue = 0;
boolean keepGoing = true;
if (input.matches("addition"))
{
while (keepGoing == true)
{
System.out.println("Next digit = (Type the digit)");
additionValue = additionValue + scan.nextInt();
System.out.println("Any more digits? Type y/n");
if (scan.next().matches("Y|y"))
{
keepGoing = true;
}
else if (scan.next().matches("N|n"))
{
keepGoing = false;
}
else
{
System.out.println("Great, you broke it.");
System.exit(1);
}
}
}
}
I've managed to get the code working by using
System.out.println("Any more digits? Type y/n");
String yayOrNay = scan.next();
if (yayOrNay.length()==1 && yayOrNay.charAt(0)=='y')
{
keepGoing = true;
}
but that seems a little too complicated to me for all that it's doing.
scan.next() pulls a new character from the input steam.
So when you check for 'n' and scan.next().matches("Y|y") executes, it is actually skipping 'n' for your next comparison.
The solution is to assign scan.next() into a variable you can use:
while (keepGoing == true)
{
System.out.println("Next digit = (Type the digit)");
additionValue = additionValue + scan.nextInt();
System.out.println("Any more digits? Type y/n");
String next = scan.next();
if (next.matches("Y|y"))
{
keepGoing = true;
}
else if (next.matches("N|n"))
{
keepGoing = false;
}
else
{
System.out.println("Great, you broke it.");
System.exit(1);
}
}
This is because you call scan.next() two times.
You have to call it one time, putting the resulting string in a variable.
String input2 = scan.next();
if (input2.matches("Y|y"))
{
keepGoing = true;
}
else if (input2.matches("N|n"))
{
keepGoing = false;
}
You need to enter 'n' twice because you scan for input in each if condition. So if the letter is not a 'y', your program will wait for user input in the next if statement.
You can simply do:
String yayOrNay = scan.next();
if (yayOrNay.matches("Y|y"))
{
keepGoing = true;
}
else if (yayOrNay.matches("N|n"))
{
keepGoing = false;
}
...
if (scan.next().matches("Y|y"))
{
keepGoing = true;
}
else if (scan.next().matches("N|n"))
You call scan.next twice
1st time you check if its Y, if it isn't you read from input again
so
somevar=scan.next()
if (somevar.matches("Y|y"))
{
keepGoing = true;
}
else if (somevar.matches("N|n"))
{
keepGoing = false;
}
else ..
Your error is to call scan.next() twice, which requests two imputs.
private int add(String input)
{
int additionValue = 0;
boolean keepGoing = true;
if (input.matches("addition"))
{
while (keepGoing == true)
{
System.out.println("Next digit = (Type the digit)");
additionValue = additionValue + scan.nextInt();
System.out.println("Any more digits? Type y/n");
String s = scan.next();
if (s.matches("Y|y"))
{
keepGoing = true;
}
else if (s.matches("N|n"))
{
keepGoing = false;
}
else
{
System.out.println("Great, you broke it.");
System.exit(1);
}
}
}
}
Please Try This,
Scanner scan = new Scanner(System.in);
int additionValue=0;
while (true)
{
System.out.println("Any more digits? Type y/n");
if (scan.next().matches("Y|y"))
{
System.out.println("Next digit = (Type the digit)");
additionValue = additionValue + scan.nextInt();
//System.out.println("Any more digits? Type y/n");
}
else
{
System.out.println("Thanks");
break;
}
}
I am not sure whether this logic will work for you. 'If you want you can process 'n' also'
output
Any more digits? Type y/n
y
Next digit = (Type the digit)
5
Any more digits? Type y/n
n
Thanks

Boolean bug (FibonacciNumbers)

First of all I am not asking anyone to do anything just need a little help to fix this bug with boolean. I put false but the program stops. I got two parts to the program.
First part where i did the calculations:
class FibonacciNumbers {
FibonacciNumbers() {} //default constructor
public int fOf(int n) {
if (n == 0) //the base case
{
return 0;
} else if (n == 1) {
return 1;
} else {
return fOf(n - 1) + fOf(n - 2);
}
}
}
Second where the main method is:
import java.util.*;
public class FibonacciNumbersTesters {
public static void main(String[] args) {
FibonacciNumbers fNumbers = new FibonacciNumbers(); //creates new object
Scanner in = new Scanner(System.in);
String again;
String test;
boolean IsRepeat = true;
boolean isQuit;
try {
isQuit = false;
while (!isQuit) {
System.out.print("Enter the number you want to convert to Fibanocci('q' to quit): ");
int n = in.nextInt();
System.out.print("The Fibanocci number for " + n + " is: ");
n = fNumbers.fOf(n);
System.out.println(n);
System.out.print("Do you want to run again? (Y or N): ");
again = in.next();
if (again.equalsIgnoreCase("N")) {
System.out.println("Thank you! Please terminate the program by entering 'Q' or 'q' OR you can cotinue by entering anything else: ");
String toQuit = in.next();
if ((toQuit.charAt(0) == 'q') || (toQuit.charAt(0) == 'Q')) {
System.out.println("Good-bye!");
isQuit = true;
}
} else {
IsRepeat = true;
}
}
} catch (InputMismatchException ex) {
test = in.nextLine();
if ((test.charAt(0) == 'q') || (test.charAt(0) == 'Q')) {
System.out.println("Good-bye!");
isQuit = true;
} else {
System.out.println("Invalid input!");
System.out.println("Try again! ");
isQuit = false;
}
}
}
}
This part where i put isQuit = false; at the end it just stops. I want it to continue.
Try putting your try catch statement inside of your while loop.

Categories