This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed last year.
I'm a beginner in coding and would appreciate any feedback. This code seemed easy but I'm not sure why the "STOP" exit condition isn't being fulfilled.
Code:
```
import java.util.Scanner;
import java.util.ArrayList;
public class U7_L2_Activity_One{
public static void main(String[] args){
System.out.println("Please enter words, enter STOP to stop the loop.");
Scanner scan=new Scanner(System.in);
ArrayList<String> list=new ArrayList<String>();
String x;
while(true){
x = scan.nextLine();
if (x = = "STOP")
{
System.out.println(list);
for (int i = 0; i <= list.size()- 1; i++){
System.out.println(list.get(i));
}
System.exit(0);
}
else{
list.add(x);}
}
}
}
So basically you want your program to end if the variable X is equal to the word "STOP" right? So in that case you need to change de comparison inside if.
In java you can't compare strings using the operator ==. When you do that you're comparing if the objects reference are equal.
Solution:
To compare Strings you can use YourVariable.equals(SomeString). In your case just change x=="STOP" to x.equals("STOP")
For reference:
Strings Method Equals: https://www.w3schools.com/java/ref_string_equals.asp
Related
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;
}
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 5 years ago.
public class ex1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Please enter a series of strings each followed by the enter key. When you'd like to end thr program simply type 'quit': \n");
Scanner scan = new Scanner(System.in);
ArrayList<String> inputList = new ArrayList<String>(); // creates a list to store user input
String input = scan.nextLine(); //takes the scanner input
while(input != "quit") { //makes sure its not equal to quit
//System.out.println(input);
inputList.add(input);
input = scan.nextLine();
}
scan.close();
System.out.println("The number of strings enetered was: " + inputList.size());
System.out.println("The strings you entered were as follows");
for (String i: inputList) {
System.out.println(i);
}
}
}
I'm trying to use the preceding code to take a series of inputs from a user using the enter key and if they enter quit I end the program. However the condition is never satisfied and the while loop never ends and I can't understand why
while(!input.equals("quit")) { //makes sure its not equal to quit
//System.out.println(input);
inputList.add(input);
input = scan.nextLine();
}
You should use equals method as shown above to compare strings. Java provides equals method to compare the contents of two strings. == and != operators are used in comparing object equalities.
a == b returns true if, and only if, a points to the same object as b
The equals method should be used, as the String class implements it so that, if a contains the same characters as b, it would returns true.
while (!input.equals("quit")) { ... }
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
I want to make a program that copies strings into a vector until the hold string is set to a certain value, at which point the program should print out the elements of the array.
I'm not sure how the in.nextline() function works, so it could be that I'm not erasing previous entries from hold, or is it that my if(hold=="0") check is simply not valid java?
import java.util.*;
import java.util.Scanner;
public class startingPoint
{
public static void main(String roark[])
{
String hold;
boolean finished=false;
Scanner in = new Scanner(System.in);
Vector<String> vec = new Vector<String>();
while(finished==false){
System.out.print("Enter the string you'd like to save, or enter 0 to print out saved strings\n");
hold=in.nextLine();
if(hold=="0"){
for(int looper=0;looper<vec.size();looper++){
System.out.print(vec.get(looper));
System.out.print("\n");
}
finished=true;
}else{
vec.add(hold);
}
}
}
}
You need to use equals method:
if("0".equals(hold){
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
This is the program
import java.util.Scanner; //imports class
public class blank2 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
boolean valid = true;
String ans;
ans = in.next(); //answer is a string
If you type in "y", it goes right to the else statement.
while (valid == true)
{
it always skips this statement
if (ans == "y")
{
System.out.println("it works");
valid = false;
{
else
{
System.out.println("no work");
valid = false;
{
}
}
}
It just wont work
if (ans == "y")
Don't compare strings with ==. That compares object references(the same string). Use:
if ("y".equals(answer))
instead. It will compare strings for equality(check if they are identical as opposed to the same one). I do not use answer.equals("y") due to the risk of a null pointer exception if answer was null for any reason.
In strings, don't use the ==, you can use compareTo instead.
if ("y".comprateTo(answer))
With this method you can check if they are the same, or if one is greater than the other.
let us know if you have questions
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do I compare strings in Java?
What am I doing wrong? After I compile and run the program, I type in my input and no matter what it is, the program always takes it as an incorrect input and says I'm wrong, here:
import java.util.Scanner;
public class mena3 {
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
String Capitol;
System.out.print("Enter the capitol of Morocco: ");
Capitol = user_input.next();
if(Capitol == "Rabat") {
System.out.println("Good Job!");
}
else {
System.out.println("That is incorrect");
}
}
}
And after I put in Rabat, it says That is incorrect. If I put in l, it says That is incorrect. Why can't I win?
Don't compare Strings using ==. Use the equals(...) or the equalsIgnoreCase(...) method instead. Understand that == checks if the two objects are the same which is not what you're interested in. The methods on the other hand check if the two Strings have the same characters in the same order, and that's what matters here. So instead of
if (fu == "bar") {
// do something
}
do,
if ("bar".equals(fu)) {
// do something
}
or,
if ("bar".equalsIgnoreCase(fu)) {
// do something
}
Voting to close this question as it's only been asked and answered umpteen million times on this site.
One of the most common mistakes in java. String require a .equals() rather than an ==.
Wrong:
if (str == "foo") {
}
Right:
if ("foo".equals(str)) { // done in this order to avoid NPE
}
Your code is perfect, only your comparison method is wrong. All other languages treats == as comparison operator. But in case of Java it is little bit tricky. Here in Java == is taken as comparison operator for objects, not a string variable.
So, to compare two Strings you have a method called `.equals() which is from String class it self.
hence you need to change your code accordingly,
import java.util.Scanner;
public class mena3
{
public static void main(String[] args)
{
Scanner user_input = new Scanner(System.in);
String Capitol;
System.out.print("Enter the capitol of Morocco: ");
Capitol = user_input.next();
// if(Capitol == "Rabat") // your previous code
if(Capitol .equals ( "Rabat") ) // new updated comparison code
{
System.out.println("Good Job!");
}
else
{
System.out.println("That is incorrect");
}
}
}