Compilation Error in a very silly program - java

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";}

Related

Java Loop only running once

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.

Java: while loop not working

I want to check the users input when a new game is created, and see if it is y, n, or neither.
For some reason it skips the while loop all together and just outputs "Welcome to Questions."
import java.util.Scanner;
public class Questions {
public static final Scanner INPUT = new Scanner(System.in);
private boolean ans;
public Questions() {
while (ans = false) {
System.out.print("Do you want to start a new game (y/n)?: ");
String input = INPUT.nextLine();
if (input == "y"){
ans = true;
//some code
}
else if (input == "n"){
ans = true;
//some code
}
else {
System.out.println("Invalid input, Try again");
ans = false;
}
}//end while
}
public static void main(String[] args) {
Questions game = new Questions();
System.out.println("Welcome to Questions.");
}
while (ans = false) {
Should be:
while (ans == false) {
= is for assignment == is for checking equality
Also Strings are compared using .equals() or .equalsIgnoreCase() not ==:
if (input == "y"){
Should be:
if (input.equalsIgnoreCase("y")){
Change private boolean ans to
private boolean ans = false;
or use do while loop
Also comparison is done using == not =

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

Data validation in Java [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
Well let's just say that this used to work fine then I started it up again today and now it doesn't....
pin is 1234 and no matter what I do it says it's not valid...
and yes I know that it doesn't check the third time. I have to fix that too:
import java.util.Scanner;
import java.util.Scanner;
public class ATM
{
public ATM()
{
Scanner console = new Scanner(System.in);
final String pin = "1234";
String userPin = "";
int pinCount = 1;
boolean error = false;
do{
System.out.print("Enter PIN: ");
userPin = console.nextLine();
if (pinCount == 3) {
System.out.println("Bank account is blocked");
break;
}
else if (userPin.length() < 4 || userPin.length() > 4) {
error = true;
pinCount += 1;
}
else if (isNumeric(userPin) && userPin == pin && pinCount < 3) {
System.out.println("Your PIN is correct");
break;
}
else{
System.out.println("Your PIN is incorrect");
error = true;
pinCount += 1;
}
}while(error);
}
public static boolean isNumeric(String str)
{
try
{
double d = Double.parseDouble(str);
}
catch(NumberFormatException nfe)
{
return false;
}
return true;
}
}
Don't ask me why I have it split:
public class ATMtest
{
public static void main(String[] args)
{
ATM atm = new ATM();
}
}
Any help would be greatly appreciated.
You don't compare String objects with ==. You should use the equals() method. I know it does not make sense if you are new in java but == means "are they the same reference?" and equals() means "are they equal?".
userPin == pin should be userPin.equals(pin)
You declare two String variables in your code:
final String pin = "1234";
String userPin = "";
and you validate them whether they are equal to or not.
else if (isNumeric(userPin) && userPin == pin && pinCount < 3) {
System.out.println("Your PIN is correct");
break;
}
String comparison should be used equals method rather than ==
Change
userPin == pin
To
userPin.equals(pin)
For digit match with exact 4 length use \d{4} regex and remove all boilerplate code on if else statement for validation.
public static boolean isNumeric(String str) {
Pattern p = Pattern.compile("\\d{4}");
Matcher matcher = p.matcher(str);
return matcher.matches();
}
For String comparison use equals method inted of == . Change it from
else if (isNumeric(userPin) && userPin == pin && pinCount < 3) {
To
else if (isNumeric(userPin) && userPin.equals(pin) && pinCount < 3) {
Change this as
else if (isNumeric(userPin) && userPin == pin && pinCount < 3) {
System.out.println("Your PIN is correct");
break;
}
this
else if (isNumeric(userPin) && userPin.equals(pin) && pinCount < 3) {
System.out.println("Your PIN is correct");
break;
}
Would a switch not be better here instead of all those if conditions?

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