Scanner nextLine() doesn't seem to change string - java

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).

Related

What's a better or more standard way to perform this function?

I am a java beginner, and in this particular problem I practiced making a program that converts any given string to lowercase string. Is there a a better way to achieve this goal in java (in terms of design)?
Also, how does the "else" (after "else if") catches or waits for me to make an input. Somehow that part does not make sense to me, even though I achieved what I wanted. How is the value of "ans" from input transferred to the entire loop and used until the loop is closed?
After many attempts and failures, I used a separate method for the conversion part. My second question is a bit too complicated to be researched.
import static java.lang.System.out;
import java.util.Scanner;
public class MyClass {
public static Scanner s = new Scanner(System.in);
public static String ans;
public static void main(String args[]) {
Conversion();
do {
ans = new String(s.nextLine());
if (ans.equalsIgnoreCase("Y")) {
Conversion();
} else if (ans.equalsIgnoreCase("N")) {
out.println("Thank you for using this program!");
break;
} else {
out.println("Invalid entry!");
out.println("Would you like to convert another string?\n(Please type 'Y' for yes, or 'N' for no.)");
}
} while (ans != "N");
}//END MAIN
public static void Conversion() {
out.println("Please enter string to be converted to lowercase: ");
String str = new String(s.nextLine());
out.println("Your new string is: " + str.toLowerCase());
out.println("Would you like to convert another string? (Y/N)");
}
}
I notice a few issues; Conversion looks like a class-name (Java naming convention would be conversion) and ans != "N" is using == instead of .equals - and wouldn't ignore case (!ans.equalsIgnoreCase("N")). Globals (e.g. static) are bad (pass the Scanner to the methods that need it), and the static import just makes the code more difficult to reason about (in my opinion). Your current loop doesn't really follow a conventional form, I would extract the prompt and loop for "another" conversion to a new method and if you must print a thank you I'd do so after the "main loop". Something like,
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
do {
conversion(sc);
} while (another(sc));
System.out.println("Thank you for using this program!");
}
public static void conversion(Scanner s) {
System.out.println("Please enter string to be converted to lowercase: ");
System.out.printf("Your new string is: %s%n", s.nextLine().toLowerCase());
}
public static boolean another(Scanner s) {
while (true) {
System.out.println("Would you like to convert another string? (Y/N)");
String ans = s.nextLine();
if (ans.equalsIgnoreCase("Y")) {
return true;
} else if (ans.equalsIgnoreCase("N")) {
return false;
}
System.out.println("Invalid entry!");
System.out.println("(Please type 'Y' for yes, or 'N' for no.)");
}
}
Answering your first question:
There are many design patterns and practices so many people can argue what I would recommend you to do. It's basically the same for all programming languages. Let's take your function "Conversion". The name itself says that you use it to convert stuff. Not to display, not to prompt - to convert. In this case, the only actual thing it should do is to convert upperCase to lowercase. In fact, you might want to specify what type of conversion it has in the name of the function (convertToLowerCase?). In fact, in Java, we use lowerCamelCase for all function names and UpperCamelCase for classes.
If you accept my previous suggestion, you could break the Conversion function into multiple ones like promptUserForInput, WrongInputHandler and so forth.
If I understood your second question correctly, you wonder about the way the code executed and how the variable ans is transferred further into the loop. Let's take a look at your code and what variables do:
You initialize your variable in the class MyClass by making it accessible to all methods in the class;
You prompt the user for the input to assign to this variable inside the do..while loop with this line ans = new String(s.nextLine()); which saves the value of the variable and, again, which can be accessed inside the whole class so its value is changed.
It goes into the if..else if...else statement. The way it works, it goes line by line - if the first if-statement fails, it goes on until it finds a truthy statement and it doesn't go any further. In your case, if the ans is not equal to either y/Y/ it will go to else if statement and if it's not n/N, it will go to else (so basically whatever except y/Y/n/N) and will be executed. After that, it jumps into the while (ans!= "N"); line where it compares your class-member variable ans and if it's not equal to "N" it starts over the loop right after the do{ part until you type in the "N".
I hope that makes sense. Whenever the program is asking you for input, it does not execute code further but is stuck until you provide any input. The value from input itself isn't passed throughout the loop and the program. The reason why you can use it because you created a higher-scope variable ans where you saved the result of your input.
IMPORTANT: if you've declared the ans inside the do..while loop, you would've not been able to have accessed it in the while (ans...) because it will 'die' right before the curly brace between do { ...here} while(). If you want to learn more about the scope and variables in general, you can read this article.
Here is my code example:
public static void main(String args[]) {
//declare before entering the loop to have higher scope
String ans = "y";
do {
//we get the given string to convert from the user
String str = promptForString();
//we convert the string
str = converseStringToLowerCase(str);
//display the string (could use another function for that: easier to debug and locate problems and in bigger projects)
out.println("Your new string is: " + str);
//prompt user for respond to continue or not
ans = promptForContinue();
handleResponse(ans);
} while (!ans.equals("n"));
}//END MAIN
//prompts user for an input string
public static String promptForString() {
out.println("Please enter string to be converted to lowercase: ");
String str = new String(s.nextLine());
return str;
}
//converts any given string to lower case
public static String converseStringToLowerCase(String str) {
return str.toLowerCase();
}
//is used to prompt user for reply
public static String promptForContinue() {
out.println("Would you like to convert another string? (Y/N)");
String str = new String(s.nextLine());
//is good to make if...else statements easier - it will always be lower case (or upper if you prefer)
return str.toLowerCase();
}
//easier to locate other response scenarios
public static void handleResponse(String response) {
if (response.equals("n")) {
out.println("Thank you for using this program!");
//it's not a very good practice to innaturally break loops. Use input for that in while(..) statement
// break;
} else if (!response.equals("y")) {
out.println("Invalid entry!");
out.println("Would you like to convert another string?\n(Please type 'Y' for yes, or 'N' for no.)");
}
}

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)) {
}

Java Scanner: Continuous loop

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.

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.

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