Java Scanner: Continuous loop - java

When I input any valid option (A,B,C) the if statement thinks that option is anything but A, B, or C, and will lead into a continuous loop.
package other;
import java.util.Scanner;
public class Menu implements InterfaceMenu{
private String option;
public void greeting(){
System.out.println("This program will use the Pythagorean Theorem");
System.out.println("to calculate a missing side.\n");
System.out.println("Choose an option!\n");
System.out.println("Choose Option A for missing side c");
System.out.println("Choose Option B for missing side b");
System.out.println("Choose Option C for missing side a\n");
}
public String optionGet(){
System.out.print("Choose an option: ");
Scanner ad = new Scanner(System.in);
option=ad.next().toUpperCase();
if( (option=="A") || (option=="B") || (option=="C") ){
ad.close();
}
else{
optionGet();
}
return option;
}
}

Aside from using the wrong method to compare strings, there is another serious problem: optionGet() opens a new Scanner on system.in. If the input contains an option that is not A, B, or C, then optionGet() calls itself recursively. The recursive call does another
Scanner ad = new Scanner(System.in);
while the first one is still open. There is no telling just what that will do, but it is likely to cause problems. Do not do that. Don't use recursion. It's inappropriate here. Instead, put the code that checks for options in a loop, and make sure new Scanner is outside the loop.

use option.equalsIgnoreCase("A") instead of ==. because == compares the reference variables and equals compars the content .

In Java strings cannot be compared using the == identifier in the same way as you would for integers. Instead you can use String.equals().
For what you have written however it may be best to compare characters however that will require changing the returned variable type within optionGet() to public char optionGet(). Doing this however will also require you to change the type of option to char. Changing the type to char will allow you to compare characters using ==.
Also be sure to define Scanner ad outside of optionGet() as your current code is redefining it for every reiteration.
Your call as to what you think is easier.

Use the the String.equals() method. Not the == comparator. Whereas .equals() checks for equality between strings, == checks if their references are the same, which isn't what you want to do.

Related

In Java, what is the functional difference between using the "==" operand and the "variable.equals(param)? [duplicate]

This question already has answers here:
What is the difference between == and equals() in Java?
(26 answers)
Closed 10 months ago.
I am within my first year of CS and near the end of my first Java themed course so I'm not quite sure how to find the answer to my question myself.
While writing some code for a project I created my input scanner as:
Scanner scanner = new Scanner(System.in);
I am taking user inputs as strings via a variable assignment:
String userInput = scanner.nextLine();
the user should only be entering strings of char "1" - "6" and "q" (to quit app)
What I'm using that works currently is as follows:
userInput = scanner.nextLine();
while (!appQuit) { //So long as user doesn't quit application
if (userInput.equals("q")) {
appQuit = true;
}
else if (userInput.equals("1")) { //Menu selection for intake a new dog
intakeNewDog(scanner);
displayMenu();
userInput = scanner.nextLine();
}
//removed "2" - "6" for brevity
else {
System.out.println("Not a valid input");
displayMenu();
userInput = scanner.nextLine();
}
}
The only way I found to check equality was the userInput.equals() function.
When I originally wrote it I tried using:
if (userInput == "1") { code }
but it would never successfully compare values as I thought it would.
Any insight into why one method works over the other? Or where I should be looking for these answers?
-Jonesy
The == equal operator compares the object references where the equals function compares the value.
For primitive types and enums the == equal operator compares the value.
An exception happens for comparing strings in a switch case statement since it internal uses the equals method.
As a rule of thumb, always use equals comparison for String. There maybe is, but i have not seen a case where reference comparison was important.
https://docs.oracle.com/javase/8/docs/technotes/guides/language/strings-switch.html
Also interesting:
What makes reference comparison (==) work for some strings in Java?
In simple words, == checks if both objects point to the same memory location whereas . equals() evaluates to the comparison of values in the objects. You can override the equals method to do more specific things, but that's the just of it.
This is literally the first thing that appears if you search java == vs equals in google.
While you might be trying to compare two strings, the operator == does not behave in java as it does in other languages.

Java String Conditional Break Not Working [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
I wrote a simple program which prompts the user to enter a sentence, word, or number, and then prints input is art. I put the program on an infinite loop so that the prompt would repeat. However, now I'm trying to add a way to quit by saying if (input == "quit") break; however it does not seem to be working. It just continues the infinite loop. Here is the full code:
import java.util.Scanner;
public class Art
{
public static void main(String [] args)
{
Scanner input = new Scanner(System.in);
String a;
for ( ; ; )
{
System.out.println("Please enter something: ");
a = input.nextLine();
if (a == "quit") break;
System.out.print("\n");
System.out.println(a + " is art.");
System.out.print("\n");
}
}
}
Any help would be lovely, thanks!
Use input.equals("quit").
The == is used to check whether two objects are the exact same instance - the same thing in memory -which the typed word and the constant string "quit" are not. Two instances of "quit" were created: one typed by the user, and one constant in the program.
The equals() method is used to compare whether two objects are equal in whatever way equality is defined for them. For strings, that would mean having the same text.
The difference between == and equals() is really fundamental in Java, so you should go over it. Here's a good SO post on the topic. Once you start creating your own classes, you will probably be implementing equals() methods for them. For that reason, make sure to go over the equals() / hashCode() contract as well.
looks like the a == "quit" is the problem. Compare strings using equals()
if("quit".equals(a)) {
}

If statement needs to accept multiple forms of user input String data type

I'm very new to Java. Currently, I'm trying to create a game of Rock Paper Scissors, which I've actually already done. My problem lies within a mechanism of trying to ask the player if they want to play at the start of the program. If so, they can enter "YES" or "yes" or "y"/"Y", if not, then "NO"/"no"/"n"/"N" and so forth.
Currently, I am storing the answer that the user gives in a String data type variable. In an "if" statement below that, I am trying to check if the answer is Yes. If so, the game initializes. If "No", the program exits. However, the boolean operator "Or" isn't quite working for me at the moment. Here's how my code is set up:
import java.util.Scanner;
import java.util.Random;
public class Game
{
public static void main(String args[])
{
// Create Scanner Object
Scanner get = new Scanner(System.in);
Scanner input = new Scanner(System.in);
// Create variables
String name, go;
int gonum=0;
System.out.printf("WELCOME TO ROCK PAPER SCISSORS. WE TAKE THIS GAME SERIOUSLY.\n\n");
System.out.printf("USER, WHAT IS YOUR NAME?\n");
name = get.nextLine();
System.out.printf("\nWELCOME, %S, TO ROCK PAPER SCISSORS.", name);
System.out.printf("\n\nDO YOU WISH TO PLAY?\n");
go = input.nextLine();
if(go == "YES" || go == "yes" || go == "Yes" || go == "y")
{
System.out.printf("LET'S PLAY SOME ROCK PAPER SCISSORS!");
}
}
}
You can check if the string equals "yes" or "no" by using any of these methods.
e.g go.equal("no") || go.equal("yes")
equals(Object anObject)
Compares this string to the specified object.
equalsIgnoreCase(String anotherString)
Compares this String to another String, ignoring case considerations.
Another way is to use the Contain boolean method
contains(CharSequence s)
Returns true if and only if this string contains the specified sequence of char values.
e.g go.contains("y") || go.contains("n")
More String Methods
You need to learn How to compare the two Strings in java
compare the strings using equals() not with ==
change if(go == "YES") to if(go.equals("YES"))
== equality operator is used for compare the two Objects
The difference between the equals == operator and the "equals" method, is that the == operator is a boolean operator used between two primitive data types. Such as two ints or doubles you may be doing a boolean test on. The "equals" method is a method of the String class and tests whether two Strings are alike. You would used the String "equals" method as such, bucket.equals(mop); . The bucket and mop variables would both hold Strings.

Scanner nextLine() doesn't seem to change string

So my problem is I'm trying to make a very simple program to refresh my terrible coding skills, but I've run into a problem I don't understand. The program is supposed to take the answer "Yes" and print "yay", just to check if it worked, but it doesn't work. So I'm wondering what I'm doing wrong.
public class main {
/**
* #param args
*/
public static void main(String[] args) {
int playerTroops, computerTroops;
String teamName, computerName = "Orcs", answer;
Scanner listener = new Scanner(System.in);
System.out
.println("Welcome to the Battle Grounds, where you are responsible for winning a war \nAre you ready? \nYes or No");
answer = listener.nextLine();
if (answer == "Yes")
System.out.println("Yayy");
else
System.out.println("Why");
}
}
For Java String comparison, you must use the .equals operator:
if(answer.equals("Yes"))
If you want to ignore case,
if(answer.equalsIgnoreCase("Yes"))
In Java, the operator == checks for reference equality. Under normal circumstances, equal strings don't automatically have same reference (I.E: They are different objects. This distinction is utterly important in Java).

Beginner Java strings [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do I compare strings in Java?
So, I have a question regarding the testing operators and strings. I'm trying to write a program that will take in user input of either "boy" or "girl". When the user inputs "boy", the output should be "You are a boy." When the user inputs "girl", the output should be "You are a girl."
However, when I compile and run the program, no matter what I input, the output is always "You are a girl."
Is this because the strings have no actual value like integers and therefore, testing operators cannot be used to compare them?
Also, is there anything like the assert function from python in java?
import java.util.Scanner;
class apples{
public static void main(String args[]){
System.out.println("Are you a boy or a girl?");
Scanner lalala = new Scanner(System.in);
String text = lalala.nextLine();
if (text == "boy"){
System.out.println("You are a boy.");
}
else{
System.out.println("You are a girl.");
}
}
}
Thanks a lot~
Use
text.equals("boy")
instead of
if (text == "boy")
The reason is, In Java, == always just compares two references (for non-primitives, that is) - i.e. it tests whether the two operands refer to the same object.
However, the equals method can be overridden - so two distinct objects can still be equal.
But the better option is to use equalsIgnoreCase, the reason is that user may enter boy or BOY or Boy or any other combination. equalsIgnoreCase method just ignores the case and compares two strings.
text.equalsIgnoreCase("boy")
Side note. Input other than Boy will get you to print Girl. Put one more extra if condition. Also before going for comparision, being on safer side trim the string for blank spaces.
Use
text.equals("boy")
or
text.equalIgnoreCase("boy")
if its not case sensitive.
instead of
if (text == "boy")
Your coade will be something like this
import java.util.Scanner;
class apples{
public static void main(String args[]){
System.out.println("Are you a boy or a girl?");
Scanner lalala = new Scanner(System.in);
String text = lalala.nextLine();
text = text.trim();
if (text.equalIgnoreCase("Boy")){
System.out.println("You are a boy.");
}
else if(text.equalIgnoreCase("Girl")){
System.out.println("You are a girl.");
} else {
System.out.println("Invalid Gender");
}
}
}
use text.equalsIgnoreCase("boy")
if you think about case also it will check content of string is same.
== is used to check for object equality.
text.equals("boy") is ok if you not consider about case.
Please use equals method for string like : if (text.equals("boy")){
== is not for string contents equality check in java
== tests if object identity is the same. When you have two string objects containing the same value this object identity won't be equal. Use the equals function to test for logical equivalence.
Your if else is wrong. Use only if here. Otherwise,
If I entered "some text", the output will be "You are a girl"
Like this
if (text.equalsIgnoreCase("boy")) {
System.out.println("You are a boy.");
}
else if (text.equalsIgnoreCase("girl")) {
System.out.println("You are a girl.");
} else {
System.out.println("You are neither a boy nor a girl");
}
It would be best to use the .equals method instead of == boy
For your other question regarding assert:
Java has an assert function. This is the sample code.
assert(x <= 50): "Not Accepted";
This code checks if integer x is greater than 50. You will see the output at the console.

Categories

Resources