This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
I'm trying to figure out why my function isn't working as it should. The code is fairly basic and self explanatory. Here is the function:
public static void Greet(){
System.out.println("Hello, what is your name? ");
name = scan.nextLine();
do{
System.out.println("Would you like to order some coffee, " + name + "? (y/n) ");
input = scan.nextLine();
if(input == "y"){
System.out.println("Great! Let's get started.");
break;
}
else if(input == "n"){
System.out.println("Come back next time, " + name + ".");
System.exit(0);
}
else{
System.out.println("Invalid response. Try again.");
}
}
while(true);
}
Basically, regardless of what I enter as "input" on line 5, the function will treat it as if I hadn't entered a 'y' or 'n', it just constantly loops the while(true) and printing "Invalid response. Try again." I have no idea why my if/else statements aren't working correctly. Any help would be appreciated, thanks!
Compare String by equals not by ==
if((input.trim()).equals("y")){
equals compares the value
== comapres the reference
Compare with equals.
if(input.equals("y")){
System.out.println("Great! Let's get started.");
break;
}
else if(input.equals("n")){
System.out.println("Come back next time, " + name + ".");
System.exit(0);
}
Related
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) {
...
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
My goal is to store the amount of correct answers into the 'correctOutOf' method, which will then return the value of corrAns when called int the /*Wrapping Up*/ section of the example code below:
import java.util.Scanner;
public class littleQuiz {
public static void main(String[] args){
Scanner key = new Scanner(System.in);
char yesno;
int answer;
/*Welcome/Splash Screen*/
/*Ask if ready and accept yes or no with appropriate return response*/
System.out.print("Are you ready for a quiz? Y or N ");
yesno = key.next().charAt(0);
if (yesno == 'Y'){
/*affirmative response*/
System.out.println("Okay, here it comes!");
}
else{
/*negative response*/
System.out.println("What a wimp...");
System.exit(0);
}
/*Quiz Section*/
/*Question 1*/
System.out.println("Q1) What is the capital of Alaska?");
System.out.println(" 1) Melbourne\n" +
" 2) Anchorage\n" +
" 3) Juneau");
answer = key.nextInt();
if (answer == 3){
System.out.println("\nCorrect!!!");
/*store to function stating number of correct answers*/
}
else{
System.out.println("\nWrong.");
}
/*Question 2*/
System.out.println("Q2) Can you store the value 'cat' in a variable of type int?");
System.out.println(" 1) yes\n" +
" 2) no");
answer = key.nextInt();
if (answer == 2){
System.out.println("\nCorrect!!!");
/*store to function stating number of correct answers*/
}
else{
System.out.println("\nWrong.");
}
/*Question 3*/
System.out.println("Q3) What is the result of 9+6/3?");
System.out.println(" 1) 5\n" +
" 2) 11\n" +
" 3) 15/3");
answer = key.nextInt();
if (answer == 2){
System.out.println("\nCorrect!!!");
/*store to function stating number of correct answers*/
}
else{
System.out.println("\nWrong.");
}
/*Wrapping Up*/
System.out.println("Overall, you got " + correctOutOf() + " out of 3 correct.");
System.out.println("Thanks for playing!");
}
/*not sure of which access modifier to use, but none have fixed it*/
private static int correctOutOf(int answer) {
return corrAns;
}
}
I'm feeling pretty positive that my if statement is going to feed the 'correctOutOf' method simply because it is the only part of the statement that can check for a correct answer with the code as-is. (just so everyone knows my train of thought.)
Edit - if this is something more than a beginner should be messing with, thanks for pointing it out. (Biting off more than I can chew?)
Don't do that, do this at the start of main:
byte correct = 0;
Or this if you ever need to use it outside of main:
private static byte correct = 0;
Then add this to each correct answer if statement:
correct++;
And print the variable "correct".
...also, you may wish to add this function to your program, to replace "key.nextInt()", to prevent the user from crashing your program:
import java.util.regex.*;
private static final int integer() {
boolean invalid = true;
int number = 0;
while (invalid) {
String input = key.next();
if (input.matches("\\d+")){
invalid = false;
try {
number = Int.parseInt(input);
} catch (java.lang.NumberFormatException e) {
invalid = true;
System.out.print("Are you trying to break the program? Try again: ");
}
} else {
System.out.println("That's not a whole number! ");
System.out.print("Try again: ");
}
}
return number;
}
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
I am working on a VERY simple calculator with Java and it does not seem to output an answer after selecting the operation. The code is as follows:
import java.util.Scanner;
public class Calc {
public static void main(String[] args) {
Scanner keyboard = new Scanner (System.in);
Double fnum;
Double snum;
Double answer;
String operation;
System.out.println("Enter a number.");
fnum = keyboard.nextDouble();
System.out.println("Enter another number.");
snum = keyboard.nextDouble();
System.out.println("What operation do you wish for? [Multiplication, Addition, Subtraction, Division]");
operation = keyboard.next();
if (operation == "Multiplication" || operation == "multiplication" || operation == "*") {
answer = fnum * snum;
System.out.print("Your answer is: " + answer);
}
else if (operation == "Division" || operation == "division" || operation == "/") {
answer = fnum / snum;
System.out.print("Your answer is: " + answer);
}
else if (operation == "Addition" || operation == "addition" || operation == "+" || operation == "add") {
answer = fnum + snum;
System.out.print("Your answer is: " + answer);
}
else if (operation == "Subtraction" || operation == "subraction" || operation == "-" || operation == "subtract"){
answer = fnum - snum;
System.out.print("Your answer is: " + answer);
}
else {
System.out.println("This is not valid.");
}
}
}
and this is the output:
Enter a number.
6
Enter another number.
6
What operation do you wish for? [Multiplication, Addition, Subtraction, Division]
Multiplication
This is not valid.
Any help would be very appreciated.
P.S. there are no errors.
Thanks!
There are 2 problems. A problem with Scanner and with the condition
keyboard.nextDouble(), keyboard.next() etc... (all except .nextLine() ) leave the newline ( \n or Enter ) in the buffer. This can cause problems etc..
I suggest adding a delimiter using keyboard.useDelimiter("\n");. This only needs to be done once and can be done right after initialization of keyboard.
That way, it will only see the Enter as a signal to end that current input.
Also, the conditions must all be using the .equals() method or .equalsIgnoreCase() which is written as:
operation.equals("Multiplication");
or
operation.equalsIgnoreCase("multiplication");
Strings should be compared via .eqauals() method. So put in the if clause operation.equals("Multiplication")...and so on...
You are comparing strings by reference, not by their values. Use .equals() instead!
As #Sebastian said you should use equals instead of ==
You can improve it a little bit to avoid the spaces mistakes or case (upper case or lower case) issues by doing it the following way:
if (operation.trim().toUpperCase().equals("MULTIPLICATION") || operation.trim().equals("*"))
That way it will work for Multiplication multiplication but also MulTIpliCation, etc.
You can get the same result using equalsIgnoreCase also
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
I am making a basic guessing game for my first java test and i have same by an interesting problem. My if statement isn't doing what it is told but when i trace it, the outputs are the same. My Code is... ;
import java.util.Scanner;
public class Game {
public static void main(String[] arg) {
Scanner GetInput = new Scanner(System.in);
try {
String Word;
String Guess;
int attempts = 0;
boolean win = false;
System.out
.println("Hello, and welcome to the guessing game! This game is very simple; one player will enter a word when");
System.out
.println("asked, then the next player will need to guess the word Be warned player two, you only have three guesses");
System.out
.println("Let's get started. Player ONE, please enter you're word: ");
Word = GetInput.next();
System.out
.println("Okay the word has been entered, now player TWO must guess");
do {
Guess = null;
System.out.println("Guess the word: ");
Guess = GetInput.next();
System.out.println(Guess + "/" + Word);
if (Word == Guess) {
System.out.println("You won!");
break;
} else if (Guess != Word) {
attempts ++;
}
if (win == false && attempts == 3) {
System.out.println("You lose!");
break;
}
} while (attempts <= 3);
} finally {
GetInput.close();
}
}
}
you can't use == to compare strings. use equals method
this code Word == Guess will not compare Word and Guess objects for equality
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
I'm not so good at programming and can't tell why this isn't working. Whatever I input, it always go straight to the else statement.
public void pizzaIntro()
{
Scanner user_input = new Scanner(System.in);
String user_command = "null";
String apology = "I'm sorry it appears there has been some kind of mistake in your order.";
System.out.println("Welcome to " + cM + " here we strive to deliver excellent services to all our customers!");
System.out.println("The current prize for pizza is $" + bP + " and an extra $" + tP + " per topping.");
System.out.println(); System.out.println();
while(user_command != "exit")
{
System.out.print("Would you like toppings?(yes/no):");
user_command = user_input.next();
if(user_command.toLowerCase() == "yes")
{
System.out.println("Good Eat Your Pizza.");
}
else if (user_command.toLowerCase() == "no")
{
System.out.println("Well Ok Then!");
}
else
{
System.out.println(apology);
System.exit(1);
}
}
pic1.show();
}
Use equals method to compare strings. To know the difference between == and equals, read https://stackoverflow.com/questions/7311451/difference-between-equals-and-instanceof
You will get a clear idea of what to use when.
while(!(user_command.equals("exit")) {
System.out.print("Would you like toppings?(yes/no):");
user_command = user_input.next();
if(user_command.toLowerCase().equals("yes"))
{
System.out.println("Good Eat Your Pizza.");
}
else if (user_command.toLowerCase().equals("no"))
{
System.out.println("Well Ok Then!");
}
else
{
System.out.println(apology);
System.exit(1);
}
}
Use equals method instead of ==
user_command.toLowerCase().equals("yes")
In Java, == always just compares two references. Its OK to use it for primitive data types. String is not primitive datatype. String is a object. You should use equals method.
In your case you can consider using equalsIgnoreCase method to ignore the Case.
Use equalsIgnoreCase. It is more safe
public void pizzaIntro()
{
Scanner user_input = new Scanner(System.in);
String user_command = "null";
String apology = "I'm sorry it appears there has been some kind of mistake in your order.";
System.out.println("Welcome to " + cM
+ " here we strive to deliver excellent services to all our customers!");
System.out.println("The current prize for pizza is $" + bP
+ " and an extra $" + tP + " per topping.");
System.out.println();
System.out.println();
while (!user_command.equalsIgnoreCase("exit"))
{
System.out.print("Would you like toppings?(yes/no):");
user_command = user_input.next();
if (user_command.equalsIgnoreCase("yes"))
{
System.out.println("Good Eat Your Pizza.");
}
else if (user_command.equalsIgnoreCase("no"))
{
System.out.println("Well Ok Then!");
}
else
{
System.out.println(apology);
System.exit(1);
}
}
pic1.show();
}
Never compare any Java objects with "==" (only primitives like int, long, double, etc.). It should read:
if(user_command.toLowerCase().equals("yes")) {
...
}
otherwise you check if the location of the object is the same, not the content.
In this particular example you might just want to use String.equalsIgnoreCase(...) instead.