Can't figure out why my method isn't executing [duplicate] - java

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
Below is a snippet of code from a class in a simple program I'm writing that plays a simple game of Blackjack. I don't understand why the hit method isn't executing whenever, upon execution of the program, I enter "hit". It goes to the else part of the statement every time regardless of what I enter. I even added a System.out.println statement to make sure that the strings matched. I feel like I must be making a very basic mistake but I just can't seem to figure it out.
System.out.println("Would you like to hit or stand?");
Scanner input = new Scanner(System.in);
String playerDecision = input.nextLine();
//System.out.println(playerDecision);
if(playerDecision == "hit") {
hit();
}
else { System.out.println("ERROR");
}
}
public void hit(){
player.makeHand(deck.draw());
System.out.println("You have the following cards: ");
player.getHand();
System.out.println("Your hand total is ");
System.out.println(player.findHandTotal());
}

Wrong string comparison. Try
if("hit".equals(playerDecision)) {

Related

How to end do while loop with user input with if statement [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 3 years ago.
import java.util.Scanner;
public class main {
public static void main(String[] args) {
boolean a = true;
do {
Scanner input = new Scanner(System.in);
System.out.println("Press any on keyboard:");
String keys = input.nextLine();
System.out.println("You pressed:");
System.out.println(keys);
System.out.println("Your hash is:");
String B = "#B";
String hash = B+keys;
System.out.println(hash);
System.out.println("To end loop press f");
//End Loop
Scanner exit = new Scanner(System.in);
String end = exit.nextLine();
if (end=="f") {
a=false;
}
}
while(a);
}
}
I've been using python and I decided to start learning java since android studio requires it. I'm learning how to do loops again. I can't get this to work. I already looked this up I couldn't find it. How would I end this by pressing 'f'? My thought process was that once it was done going though the first lines of the do loop, it would go though the if statement changing the value of a ending the loop.
use break statement under if(){} body. also your == comparison will give false, use str1.equals(str2) for comparison.
Your problem is you are comparing strings with ==.You have to use equals to write correct if statement.
if (end.equals("f")){...}
You could use the below code to check
if (end.equals("f")) { // end == "f" , it check the reference.
a = false;
}

Java Scanner utility wont allow user to re-enter input in a loop [duplicate]

This question already has answers here:
How to handle infinite loop caused by invalid input (InputMismatchException) using Scanner
(5 answers)
Closed 6 years ago.
just trying to wrap my head around Java coding with a few practice programs and am experimenting with loops and the scanner utility and just ran into a problem when trying to use the scanner to check if the right input was entered and getting the program to loop until the right input was entered.
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int numbOne;
boolean checker;
System.out.println("please enter an Interger");
do{
if(s.hasNextInt()){
numbOne = s.nextInt();
System.out.println("Yay it worked!!!");
checker = true;
}
else{
System.out.println("I told you to enter an integer you idiot\nTRY AGAIN!!!!!!");
checker = false;
}
}
while(checker == false);
}
}
Basically what is supposed to happen is that once the program enters the loop it asks the user to input an integer, if the user inputs an integer it displays the message "Yay it worked!!!" and breaks out of the loop, however if the user inputs a string or any other value then the code loops around and should ask for the input again.
However the problem I am having is that the program only asks for the input once and if the wrong input is entered then the program just keeps looping the else statement over and over again without asking the user for the input again.
Any idea what I have done wrong?
You need to consume the next token. Try to call s.next() in the else-block.
Basically the 'hasNextInt()' method is a peek method, but it will never consume that input, and therefore keeps looking at the same input.

Continue from Label Error [duplicate]

This question already has answers here:
What is the "continue" keyword and how does it work in Java?
(12 answers)
Closed 6 years ago.
I am programming a simulated online banking client in java. I need the ability (or an alternative) to be able to continue from a label. This is a snippet from my code so far.
Main:
{
for ( ; ;) {
System.out.println("Welcome to TamarinĀ© online banking!");
System.out.println("Select register or login:");
choice = scan.nextLine();
if (choice.equalsIgnoreCase("register")) {
register:
{
System.out.println("Welcome to register! Please type your username:");
userreg = scan.nextLine();
if (accounts.contains(userreg)) {
System.out.println("Username taken! Try again.");
continue register;
Java is giving me a "continue cannot be used outside of loop" error. Any ideas as to (if the registration fails) I could bring the user back to the last step ('registration' label)? And if not, how could I get this code to work?
(I obviously have closing braces down at the end).
Well you shouldn't be using a goto in the first place (which currently doesn't exist in Java), the reason for this being that using labels promotes badly structured and difficult to maintain code (also called spaghetti code).
Instead you should add a nameTaken boolean and loop while it is true.
while(nameTaken) {
System.out.println("Welcome to register! Please type your username:");
userreg = scan.nextLine();
if (accounts.contains(userreg))
System.out.println("Username taken! Try again.");
else {
// do stuff
nameTaken = false;
}
}
First of all, thanks for using labels and taking us all back to C programming from so long ago. Second, you can easily simulate the behavior you currently have with labels by using appropriately constructed loops, e.g.
do {
System.out.println("Welcome to TamarinĀ© online banking!");
System.out.println("Select register or login:");
choice = scan.nextLine();
if (choice.equalsIgnoreCase("register")) {
do {
System.out.println("Welcome to register! Please type your username:");
userreg = scan.nextLine();
if (!accounts.contains(userreg)) {
System.out.println("Creating username " + userreg + " ...");
break;
}
else {
System.out.println("Username taken! Try again.");
}
} while (true);
}
// the rest of your logic goes here
} while (true);

While loop breaks after bufferedInput change [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 6 years ago.
I'm doing some basic homework, and it's honestly all stuff I know. But I decided to jazz it up a little, and something I'm missing is causing an unexpected error.
The idea is to use a while loop which asks if the user would like to do something. So long as they say yes, the loop continues the operations that it holds (in this case rounding a decimal to an int). However, as soon as I enter yes, or anything really, the loop breaks there and won't continue on to the rounding portion.
public class DecimalRounder {
//Main class method that starts and ends the program. It is prepared to throw an IO exception if need be.
public static void main(String args[])throws IOException
{
//Main initializes a new reader to take input from System.in
InputStreamReader rawInput = new InputStreamReader(System.in);
//Main then initializes a new buffer to buffer the input from System.in
BufferedReader bufferedInput = new BufferedReader(rawInput);
//Main initializes other used variable
double castInput = 0.0;
String contin = "yes";
//Program then sets up loop to allow user to round numbers till content
while (contin == "yes")
{
//Program asks user if they'd like to round.
System.out.println("Would you like to round? Type yes to continue... ");
contin = bufferedInput.readLine();
//If user says yes, rounding begins. ERROR FOUND HERE?
if (contin == "yes") //INPUT "yes" DOESN'T MATCH?
{
//Program then requests a decimal number
System.out.println("Please enter a decimal number for rounding: ");
String givenLine = bufferedInput.readLine();
//rawInput is worked on using a try catch statement
try {
//givenLine is first parsed from String into double.
castInput = Double.parseDouble(givenLine);
//castInput is then rounded and outputted to the console
System.out.println("Rounded number is... " + Math.round(castInput));
//Branch then ends restarting loop.
}catch(Exception e){
//If the data entered cannot be cast into a double, an error is given
System.err.println("That is not a roundable number: " + e.getMessage());
//And branch ends restarting loop.
}
}
}
System.out.println("Have a nice day!");
}
}
Use .equals instead of == to compare strings in JAVA.
Try this :
contin.equals("yes")

While loop in Java, string comparison does not work [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do I compare strings in Java?
I'm working on a small program that asks for your name using a Scanner. If you enter blankstring, then I would like the console to display a message.
Here's what I tried doing:
import java.util.Scanner;
public class Adventure
{
public static void main(String[] args)
{
Scanner myScan = new Scanner (System.in);
System.out.println("What's your name?");
String name = myScan.nextLine();
while (!(name == "")) //Always returns false.
{
System.out.println("That's not your name. Please try again.");
name = myScan.nextLine();
}
System.out.println("It's a pleasure to meet you, " + name + ".");
}
}
The code never enters the while loop. Why?
Change your condition to:
while(!name.equals("")) {
or as suggested below by m0skit0:
while(!name.isEmpty()) {
See also
why equals() method when we have == operator?

Categories