This question already has answers here:
String.equals versus == [duplicate]
(20 answers)
How do I compare strings in Java?
(23 answers)
Closed 11 months ago.
I wrote a function to receive user input. Can't get the correct answer back. Always Failure. I am losing my mind right now.
public String getChoice() {
Scanner SC = new Scanner(System.in);
System.out.print("Ready to play? (Y/N) ");
String playChoice = SC.next(); // Input Y or N
playChoice = playChoice.replace("\n", "");
System.out.println("Input length is: " + playChoice.length());
System.out.println(playChoice);
if (playChoice == "N") {
SC.close();
return "Success N";
}
else if (playChoice == "Y") {
SC.close();
return "Success Y";
}
SC.close();
return "Failure"; // Always this one works
}
Try this:
public String getChoice() {
Scanner SC = new Scanner(System.in);
System.out.print("Ready to play? (Y/N) ");
String playChoice = SC.next(); // Input Y or N
playChoice = playChoice.replace("\n", "");
if (playChoice.equals("N")) { // Replace operator '==' with 'equals()' method.
SC.close();
return "Success N";
} else if (playChoice.equals("Y")) { // Same here.
SC.close();
return "Success Y";
}
SC.close();
return "Failure"; // Always this one works
}
The reason why your code is not working as intended, is that the == operator compares whether the 2 compared object references are pointing to the same object. This obviously is not the case in your if-statements, and therefore those expressions will always evaluate to false.
the equals() method on the other hand actually compares the content of the given objects , thus delivering the desired result.
#Bialomazur gave an explanation already and here is a bit cleaner code and tips.
Actually, closing Scanner is not a good practice, but if you decided to, you can close it before your ifs just in one place, since you are not using scanner anymore.
Also, switch looks better here
public String getChoice() {
Scanner SC = new Scanner(System.in);
System.out.print("Ready to play? (Y/N) ");
String playChoice = SC.next(); // Input Y or N
playChoice = playChoice.replace("\n", "");
System.out.println("Input length is: " + playChoice.length());
System.out.println(playChoice);
SC.close();
switch (playChoice) {
case "Y":
return "Success Y";
case "N":
return "Success N";
default:
return "Failure";
}
}
Related
This question already has answers here:
Read multiple word strings with java.util.Scanner() [duplicate]
(2 answers)
Closed 2 years ago.
Still fairly new to Java and I am having trouble with this loop. the first issue is that I can only enter a single word for newName, if I try and enter more then one word, it uses the input for the newCode as well and skips through. I just can't figure out why I cant enter a name that has more then 1 word in a string. when I try and add a string with 3 words in it it skips the newCode then throws an error.
int addAnother = 1;
while (addAnother == 1) {
System.out.print("Enter a new Subject Name: ");
String newName = input.next(); //only accepting a single word...
System.out.print("Enter a new Subject Code: ");
String newCode = input.next(); // must be entered in CAPS
Subject newSubject = new Subject(newName, newCode);//create object
if (newSubject.isValidCode(newCode) == true){
System.out.println("The code meets the requirements");
if (newSubject.codeExist(newCode, subjectList) == false){
subjectList.add(newSubject);
System.out.println("Your Subject has been added");
}
else
System.out.println("The code you entered already exists");
}
else
System.out.println("Your subject code does not "
+ "meet the requirements i.e. ITC206");
System.out.println ("\nEnter a new subject? 1=Yes 2=No");
addAnother = input.nextInt();
}
I am just not sure what I am doing wrong....
Use nextLine() method instead of next().
private String read()
{
Scanner scanner = new Scanner(System.in);
return scanner.nextLine();
}
https://www.geeksforgeeks.org/difference-between-next-and-nextline-methods-in-java/
I want to make a basic game where two random numbers are generated and the user has to enter the correct product.
What am I doing wrong? thanks
import java.util.Scanner;
import java.awt.*;
public class Userinput {
public static void main (String[] args) {
String firstName;
//Create scanner to obtain user input
Scanner scanner1 = new Scanner( System.in );
int a, b, correctAnswer;
a=(int) (Math.random()*10);
b=(int) (Math.random()*10);
//obtain user input
System.out.println("Enter your first name: ");
firstName = scanner1.nextLine();
//output information
System.out.print("Hello " + firstName + " ");
System.out.println("what is " + a +" times " + b);
String answer1 = scanner1.nextLine();
correctAnswer = a * b;
if ((answer1).equals(correctAnswer))
System.out.println("Correct!");
else if (!(answer1).equals ("correctAnswer"));
System.out.println("Incorrect!");
}
}
You are comparing a String (answer1) to an Integer (correctAnswer). That's comparing apples and oranges, they are never the same.
You need to either convert the String to an int:
Integer.parseInt(answer1)
which might fail if answer1 can't be parsed as an integer; or convert the int to a String:
Integer.toString(correctAnswer)
and then compare them:
Integer.parseInt(answer1) == correctAnswer // You can use == because int is primitive.
or
answer1.equals(Integer.toString(correctAnswer))
Try this:
int answer1 = scanner1.nextInt();
int correctAnswer = a*b;
if (answer1==correctAnswer) {
System.out.println("Correct!");
} else {
System.out.println("Incorrect!");
}
There were a few issues with your code, mostly related to mixing up Strings and ints. Here is a good explanation of how to compare different data types. I would recommend that you use Scanner.nextInt() to save you having to cast Strings to integers.
I would also recommend that you do not omit the braces in your if statements. It makes your code easier to read and can avoid some confusion, especially when you are just starting out with Java.
This is where the problem is:
if ((answer1).equals(correctAnswer))
System.out.println("Correct!");
else if (!(answer1).equals ("correctAnswer"));
System.out.println("Incorrect!");
}
Do this instead:
Integer answer = Integer.parseInt( answer1 );
if (answer1.equals(correctAnswer)) {
System.out.println("Correct!");
} else {
System.out.println("Incorrect!");
}
The way that it is currently written, "Incorrect!" would always be printed, because of the semi-colon on the else if. Also, it was comparing answer1 with the literal String "correctAnswer" because of the quotes. Since they're not even the same type (int and String), equals(...) returns false. I would also suggest using curly braces. It helps to alleviate some of these issues.
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
This a simple program that asks the user for two questions. Based on the user's input, we will display a guess of what the object is. Similar to the game "20 Questions". No matter what input I give the program, it always returns the value of myGuess as "paper clip"
I have tried commenting out the inside of each if/else statement and having the output set to 1,2,3 but it still gets to 3 ( the block of the paper clip). This leaves me to think that my comparison of strings has a bug either in the assignment of the user input or conditional logic... Here is the code:
import java.util.Scanner;
public class JavaTraining {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String input1,input2;
String myGuess;
System.out.println("TWO QUESTIONS!");
System.out.println("Think of an object, and I'll try to guess it.\r\n");
System.out.println("Question 1) Is it an animal, vegetable, or mineral?");
input1 = keyboard.nextLine();
System.out.println("\r\nQuestion 2) Is it bigger than a breadbox?");
input2 = keyboard.nextLine();
if (input1 == "animal"){
if (input2 == "yes"){
myGuess = "moose";
}
else{
myGuess = "squirrel";
}
}
else if (input1 == "vegetable"){
if (input2 == "yes"){
myGuess = "watermelon";
}
else{
myGuess = "carrot";
}
}
else{
if (input2 == "yes"){
myGuess = "Camaro";
}
else{
myGuess = "paper clip";
}
}
System.out.println("\r\nMy guess is that you are think of a "+myGuess+".\r\nI would"
+" ask you if I'm right, but I don't actually care."+input1+input2);
}
}
Use .equals() for strings instead of == . Java strings are objects not primitive data types.
change this
if (input1 == "animal")
to
if(input1.equals("animal"))
Take a look at this link
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
public class ElectronicCounter {
public ElectronicCounter(User user)throws IOException{
Scanner scanner = new Scanner(System.in);
boolean done = false;
loginName = user.getName();
System.out.println("--------------------------------------------------------");
System.out.println("Welcome to the Electronic-Sales Counter! ");
while(!done){
try{
System.out.print("Please enter '1' to record sales or '2' to exit:");
input = scanner.nextLine();
System.out.println("bug");
if(input=="1"){
System.out.println("Please enter a list of purchasing-product ID and number");
done = true;
}
else if(input=="2"){
System.out.println("<LOG> User " +loginName+ " has successfully logged off! ");
done = true;
}
else{
System.out.println("<LOG> Invalid command");
}
}
catch (NoSuchElementException e){
System.out.println("<LOG> No Such Element");
}
catch (IllegalStateException e){
System.out.println("<LOG> IllegalState");
}
}
scanner.close();
}
static String loginName;
static String input;
}
The scanner doesn't stop to search the token when scanner.nextLine() is computed. I would like to ask how can I stop the scanner to wait input??Thanks
NEVER compare strings using ==. When using == to compare string objects, you are not comparing it's values but it's references.
Always compare using the equals method.
input.equals("2");
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
im only 15 and new to java so i am trying to build a simple calculator, but i cant seem to figure out why this if statement is being ignored. I have check to be sure that all values are being stored and yes they are so i can not see any other problems which would explain this. Any help would be great! Look for the comment in the second class //This if statement
The first class
public class CalculatorOperations {
double fnum, snum,answer;
String operation;
void plus(){
operation="+";
answer = fnum + snum;
}
void subtract(){
operation="-";
answer = fnum - snum;
}
void multiple(){
operation="*";
answer = fnum * snum;
}
void divide(){
operation="/";
answer = fnum / snum;
}
void invalidOperation(){
System.out.println("Invalid operation.");
}
void showAttributes(){
System.out.println(fnum);
System.out.println(snum);
System.out.println(operation);
}
}
The second class
import java.util.Scanner;
public class calculatorApplication {
public static void main(String [] args){
CalculatorOperations Operators = new CalculatorOperations();
Scanner userInput = new Scanner(System.in);
String loop2 = null;
boolean loop;
while (loop = true){
// Getting input and storing it
System.out.print("Please enter first number: ");
Operators.fnum = userInput.nextDouble();
System.out.println("TEST:"+Operators.fnum);
System.out.print("Please enter second number: ");
Operators.snum = userInput.nextDouble();
System.out.println("TEST:"+Operators.snum);
System.out.print("Please enter operation (+, -, * or /): ");
Operators.operation = userInput.next();
System.out.println("TEST:"+Operators.operation);
// this if statement
if (Operators.operation == "+") {
Operators.plus();
} else if (Operators.operation == "-") {
Operators.subtract();
} else if (Operators.operation == "*") {
Operators.multiple();
} else if (Operators.operation == "/") {
Operators.divide();
} else {
Operators.invalidOperation();
}
System.out.println("Answer: " +Operators.answer);
System.out.print("Would you like to do another sum? (yes or no): ");
loop2 = userInput.next();
}
if (loop2.equals("yes") || loop2.equals("Yes")){
loop = true;
System.out.println();
System.out.println();
}else{
loop = false;
// Closes scanner to prevent resource leaks
userInput.close();
System.exit(0);
}
}
}
Comparing Strings with == generally doesn't work the way you'd like it to. It's because Strings are Objects and == compares object references against each other, instead of checking if the Strings contain identical text.
Try String.equals instead:
if (Operators.operation.equals("+")) {
... //and of course the same for the rest of the statements
Good luck with your program!
Use the .equals(String) method, instead of ==. Your if-structure would change to this:
if (Operators.operation.equals("+")) {
Operators.plus();
} else if (Operators.operation.equals("-")) {
Operators.subtract();
} else if (Operators.operation.equals("*")) {
Operators.multiple();
} else if (Operators.operation.equals("/")) {
Operators.divide();
} else {
Operators.invalidOperation();
}
.equals(String) is used for comparing strings, whereas == is used for comparing everything else pretty much. == is comparing the reference to an object and .equals(String) is used to compare String values.
Also, change while (loop = true) to while(loop) or while (loop == true); otherwise you are indicating that you are actually changing the value of loop.
You don't want to compare strings with == because by doing that you're comparing the reference of the string, and not the value of the string. You need to use the .equals method.
if (Operators.operation.equals("+"))
From the javadoc:
boolean equals(Object anObject)
Returns true if and only if the argument is a String object that represents the same sequence of characters as this object.
Also, you need to change
while (loop = true)
to
while (loop)
= is the assignment operator, == is the comparison operator.