How to fix variable might not have been initialized [duplicate] - java

This question already has answers here:
Variable might not have been initialized error
(12 answers)
Closed 3 years ago.
I am trying to create a method that spits out a boolean value if the user enter 1 word that is included in a list of 6. otherwise prompt the user until he enters 1 corrected one
I've tried using a while loop with switch but it doesnt seem to work
/**
* If the user says yes or y or true, return boolean value of true
* if the user says no or n or false, return boolean value of false
* Display a prompt if user fails to write any of 6 above words until
* the user does
*/
public static boolean promptForYesNo(Scanner in, String prompt){
boolean toReturn;
boolean valid;
String userAnswer;
System.out.println(prompt + "Yes or No?");
userAnswer = in.next();
userAnswer = userAnswer.toLowerCase();
while (userAnswer.equals("yes") || userAnswer.equals("y") ||
userAnswer.equals("true") ||userAnswer.equals("no") ||
userAnswer.equals("n") || userAnswer.equals("false")){
if (userAnswer.equals("yes") || userAnswer.equals("y") ||
userAnswer.equals("true")){
toReturn = true;
}
else if(userAnswer.equals("no") || userAnswer.equals("n") ||
userAnswer.equals("false")){
toReturn = false;
}
else {
System.out.println(prompt + "Yes or No?");
userAnswer = in.next();
userAnswer = userAnswer.toLowerCase();
}
}
return toReturn;
}

Even if you initialize the variable, it won't satisfy your intention. Instead, you should recursively call the method again with the arguments until you expect the user's intention, like so:
public static boolean promptForYesNo(Scanner in, String prompt){
System.out.println(prompt + "Yes or No?");
String userAnswer = in.next();
userAnswer = userAnswer.toLowerCase();
if (userAnswer.equals("yes") || userAnswer.equals("y") ||
userAnswer.equals("true")){
return true;
}
else if(userAnswer.equals("no") || userAnswer.equals("n") ||
userAnswer.equals("false")){
return false;
}
else {
return promptForYesNo(in, prompt);
}
}
I have cleaned up your code a bit.

The above code goes in continuous loop: use break when condition is satisfied
while (conditions) {
if (conditions) {
toReturn = true;
break;
} else if (conditions) {
toReturn = false;
break;
} else {
System.out.println(prompt + "Yes or No?");
userAnswer = in.next();
userAnswer = userAnswer.toLowerCase();
}
}

Related

I am having trouble implementing a "while" loop in Java [duplicate]

This question already has answers here:
How is if/while condition evaluated when we use assignments instead of comparison?
(4 answers)
How do I compare strings in Java?
(23 answers)
Closed 1 year ago.
This is my code.
import java.util.Scanner;
public class passwordProgram {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String correctPassword = "WooHoo";
int tries = 0;
boolean keepGoing = true;
while(keepGoing = true) {
tries = tries + 1;
System.out.println("try #" + tries);
String password;
System.out.println("Please enter the password: ");
password = scan.next();
if(password == correctPassword) {
System.out.println("This is the correct result:" + password);
keepGoing = false;
if(tries >= 3) {
System.out.println("Too many wrong tries. Exiting program");
keepGoing = false;
break;
}
}
}
}
}
The while loop doesn't end when the right password is entered, and it keeps repeating after the allowed number of attempts has been reached and I want to know why.
Is it because of the condition statement in the while loop or is there something else wrong with the code?
while (keepGoing = true)
this doesn't verify whether keepGoing is true, it sets it to true, so it remains true.
You should change it to:
while (keepGoing == true)
or, shorter:
while (keepGoing)
EDIT:
Another problem you have, is the way you compare your String values.
if(password == correctPassword)
The == operator is used to compare references of Objects, or primitive values, not the values of Objects.
What you want here, is:
if ( correctPassword.equals(password))
Here's a good read about that:
How do I compare strings in Java?
EDIT 2:
Your conditional statements shouldn't be nested. If they are, that means the second one will only execute if the first one evaluates to true:
if(correctPassword.equals(password)) { // already corrected
System.out.println("This is the correct result:" + password);
keepGoing = false;
if(tries >= 3) {
System.out.println("Too many wrong tries. Exiting program");
keepGoing = false;
break;
}
}
should be rewritten as:
if(correctPassword.equals(password)) { // already corrected
System.out.println("This is the correct result:" + password);
keepGoing = false;
}
if(tries >= 3) {
System.out.println("Too many wrong tries. Exiting program");
keepGoing = false;
break;
}
Your condition is an assignment, not a check.
Try changing it to while(keepGoing==true).
The '=' operator sets a value to a variable. The '==' operator compares values. A good practice it would be to just write the following statement:
while(keepGoing) {
...
}
You can just parse a boolean inside the 'while' statement and it will go on while the boolean is true.
In order to check a condition you should use "==" instead of "=" so the while statement should look like this:
while(keepGoing == true) {
...
}

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

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
}

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?

Input validation checking both for duplicates and format using array and for loop [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
Hoping someone could assist. Missing something obvious I think. I have to get a user to input an account number. I need to validate this against two checks. One being that it is not yet used and that it is in the correct format.
I have played around with this and tried different ways of doing this. I think that the reason it fails is because halfway through going through the array, I am asking for user input.
It stops the for-loop and then continues from there when user has input the data. how do I validate both?
System.out.println("Please enter an ID (format PNOnnn)");
String pnoID = console.next();
boolean pnoIDValid = false;
while (pnoIDValid);
{
for (int i = 0 ; i < pno.length ; i++)
{
if (pno[i] != null)
{
if (pnoID.compareToIgnoreCase(pno[i].getmID()) == 0)
{
System.out.println("ID already used");
//pnoID = console.next();
}
else
{
if (!(pnoID.matches("PNO\\d{3}")))
{
System.out.println("Must be in format PNOnnn");
//pnoID = console.next();
}
else
{
pnoIDValid = true;
}
}
}
}
}
I wonder if this is not resulting in the array not getting checked. I have tried it this way as well. logically it makes sense to me, but it is just not working.
System.out.println("Please enter a ID (format PNOnnn)");
String pnoID = console.next();
boolean pnoIDValid = false;
while (pnoIDValid);
{
for (int i = 0 ; i < pno.length ; i++)
{
if (pno[i] != null)
{
if ((pnoID.compareToIgnoreCase(pno[i].getmID()) == 0) ||
(!(pnoID.matches ("PNO\\d{3}"))))
{
System.out.println("ID already used");
pnoID = console.next();
}
else
{
pnoIDValid = true;
}
}
}
}
I eventually went with:
int subSelection = console.nextInt();
if(subSelection == 1){
System.out.println("Enter ID");
String pnoID = cons.next();
int test1=0; int test2=0;
for (int i = 0 ; i < pno.length ; i++){
if (pno[i]!=null && pnoID.compareTo(pno[i].getmID()) == 0)){
test1 = 1;
}else{
test2 = 1;
}
}
int test3 = 0; int test4 = 0;
if (pnoID.matches("PNO\\d{3}")){
test3 = 1;
}else{
test4 = 1;
}
if (test1 == 1 && test4 == 1){
System.out.println("This ID exists or format invalid");
}else{
System.out.println("enter name (first and last)");
String name = cons.nextLine();
System.out.println("enter phone number");
String phone = cons.nextLine();
}
The odd thing however is that the first time i go through this, I am able to enter the details correctly. The second time however it is not giving me the option to enter an ID. It shows the question "enter id", but then immediately goes to the next question "enter name".
I have two scanners; one for menu selections and one for userinput. might this cause a conflict?
RESOLVED:
This has now been resolved as well. From what I have read online; with the scanner, a new line character (carriage return/enter key stroke) is left in the buffer and this is picked up, whihc results in the second console entry being skipped.
The suggested solution is to use bufferedreader nextLine() which I tried for all string entries and this has successfully resolved my issue.
Extract uniqueness check to separate method:
private boolean isIDUnique(String pnoID) {
for (int i = 0; i < pno.length; i++) {
if (pno[i] != null && pnoID.compareToIgnoreCase(pnoID)) {
return false;
}
}
return true;
}
Main method:
System.out.println("Please enter a ID (format PNOnnn)");
String pnoID;
boolean pnoIDValid = false;
do {
pnoID = console.next();
if (!isIDUnique(pnoID) {
System.out.println("ID is not unique");
} else if (!pnoID.matches("PNO\\d{3}") {
System.out.println("Invalid format");
} else {
pnoIDValid = true;
}
} while(!pnoIDValid);

Categories