Loop isn't breaking when a specific string is inputted [duplicate] - java

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
When the user inputs pBreak, it should break the while loop. However, this isn't working and I'm confused on why. Could somebody please help me?
package main;
import java.io.*;
import java.util.*;
public class TextFiles {
public static void main(String[] args) {
try {
BufferedWriter out = new BufferedWriter(new FileWriter("file.txt"));
Scanner input = new Scanner(System.in);
while (true) {
String line = input.next();
if (line == "pBreak") {
break;
}
out.write(line);
out.newLine();
}
out.close();
} catch (IOException e) {
System.out.println("Error!");
}
}
}

Use equals instead of ==. Consider, null-safe equals
if ("pBreak".equals(line)) {

Change:
if (line == "pBreak") {
to
if (line.equals("pBreak")) {
== compares object references, .equals(String) compares String values.

This code will also work:
if (line.equals("pBreak")) {
break;
}

== operator will compare the references of the two operands.
As line variable is a different string object's reference ,it will not match to string literal constant reference pBreak while comparing.
if (line .equals("pBreak")) {
break;
}
So equals() method has to be used to compare the String.enter code here

Related

while loop with if statement not working [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
String.equals versus == [duplicate]
(20 answers)
Closed 5 years ago.
By way of an example I have a txt file that contains a list of dogs, one on each line of the file and then "**" on the last line. I then have the following code to load this into an ArrayList to use in a JComboBox.
This way I can simply add another line in the text box to add another dog.
My example code is as follows
public class test{
static String temp;
public static void main(String[] args) {
List<String> picklistDogs = new ArrayList<String>();
File picklistFile = new File (filePath);
try {
BufferedReader loadPickList = new BufferedReader (new FileReader(picklistFile));
while(true) {
temp = loadPickList.readLine();
if (temp != "**") {
picklistDogs.add(temp);
} else {
break;
}
}
loadPickList.close();
}
catch(FileNotFoundException e){
System.out.println("file not found");
}
catch(IOException e){
System.out.println("file io error");
}
} // END of main
} // END of class test
My problem seams to be that the if statement never triggers the break to exit the while loop.
Any solutions would be appreciated.
Use !temp.equals("**") .Try below code
if (!temp.equals("**")) {
picklistDogs.add(temp);
} else {
break;
}
In order to compare strings better to use java.lang.String#equals

its giving true for both values in boolean. how to improve the code? [duplicate]

This question already has answers here:
What is the difference between == and equals() in Java?
(26 answers)
Closed 7 years ago.
import java.util.Scanner;
class Pal {
public static boolean Palindrome(StringBuffer str) {
StringBuffer str1 = str.reverse();
System.out.println(str1);
if (str == str1) {
return true;
} else {
return false;
}
}
public static void main(String args[]) {
System.out.println("Enter a string");
StringBuffer str = new StringBuffer();
Scanner input = new Scanner(System.in);
str.append(input.nextLine());
boolean result = Palindrome(str);
System.out.println(result);
}
}
How sholud I improve my code such that values come out to be perfectly correct?
if (str == str1)
{
return true;
}
else
{
return false;
}
is the same as
return str == str1;
However, this still "won't work" correctly because
Code should equals() for comparing objects (including Strings and StringBuffers) and
StringBuffer does not have a useful equals.
A correction, taking both of these into account, would be:
return str.toString().equals(str2.toString());
In this case we first get the current String content of both StringBuffer objects and then compare it with String.equals(String), which works as expected.
An alternative would be to bypass the StringBuffers in this case and directly use Strings; this would allow skipping the toString calls.

Java Scanner Code If-then-else [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
My if-then-else statement is always outputting the else outcome
import java.util.Scanner;
public class NiallScanner {
public static void main(String[] args)
{
System.out.println("Hello, What is your name?");
Scanner scanner = new Scanner(System.in);
String yourName = scanner.nextLine();
System.out.println("Is your name: "+yourName + "?");
Scanner scanner1 = new Scanner(System.in);
String isCorrect = scanner1.nextLine();
if (isCorrect == "Yes")
{
System.out.println("Thank you for your confirmation!");
}
else
{
System.out.println("Retry please.");
}
}
Any ideas why guys? I'm really new to java btw, so I may be overlooking basic coding errors.
Use "Yes".equals(isCorrect);, == compares object references, not content. Two different Strings can have the same content.
Alternatively you can use String.intern() to obtain unique references from the pool of strings; those can be safely compared using the == operator:
"Yes" == isCorrect.intern();
While both methods work, I would advice you to go with the first one. Use equals to compare objects and == to compare primitives.
Check out the Working example.
Use equals() method instead, because == compare object reference the bit it contain to see if two object are refering to the same object. But equals() method compare the value instead. so in this case you should do: "Yes".equals(isCorrect)
If you want to check if two object are refering to the same object for example:
Object1 x = new Object1();
Object2 y = x;
if(x == y) {
//This will return true because 'y' is refering to object 'x' so both has the bit to access the object on memory.
}
But if you want to check by value for example:
String hola1 = "hola";
String hola2 = "hola";
if(hola1.equals(hola2)){
//Return true because both has the same value.
}
Use equals method to Compare strings.== will compare the references not the content.Please find the corrected program.
public class NiallScanner {
public static void main(String[] args) {
System.out.println("Hello, What is your name?");
Scanner scanner = new Scanner(System.in);
String yourName = scanner.nextLine();
System.out.println("Is your name: "+yourName + "?");
Scanner scanner1 = new Scanner(System.in);
String isCorrect = scanner1.nextLine();
if (isCorrect.equals("Yes"))
{
System.out.println("Thank you for your confirmation!");
}
else
{
System.out.println("Retry please.");
}
}
}

Java conditional statement [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Java String.equals versus ==
I am using jcreator to practice java language. I came up with a conditional statement in which if the user input is = "test" it will print an "okay!" message. This is my code:
class conditional {
public static void main (String[] args) {
Scanner user_input = new Scanner(System.in);
String username;
System.out.print("username: ");
username = user_input.next();
if (username == "test") {
System.out.println("okay");
}
else {
System.out.println("not okay");
}
}
The above code does not show any error, it does not display the "okay" && "not okay" message either. I am not sure what's wrong with my logic.
Strings should be compared using .equals rather than ==. This is the case for all non-primitive comparisons. For example, you would compare two int fields with ==, but because Strings are not primitive, .equals is the correct choice.
if (username.equals("test")) {
You should use String.equals here.
if (username.equals("test")) {
Otherwise, you're comparing the identities of the objects rather than their semantics. In fact, you have two separate Strings here, which satisfy semantic equality.
as #veer said,
you can use equalsIgnoreCase / equals if (username.equals("test")) { ... }
Or
You can use compareToIgnoreCase / compareTo
if (username.compareTo("test")==0) { ... }
Or If you want to use == do username.intern(); Then you can use ==.
Note: Not a recommended approch just for FYI.
To compare string you need to use .equals() method and also if you need ignore the case of the letters in the String you can use .equalsIgnoreCase()
if (username.equals("test")){
}
else{
}
It will work if you do it like this:
import java.util.Scanner;
class Conditional {
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
String username;
System.out.print("username: ");
username = user_input.next();
if (username.equals("test")) {
System.out.println("okay");
} else {
System.out.println("not okay");
}
user_input.close();
}
}
A few remarks:
Class names should start with an upper case.
Use equals to compare Strings.
You state that no result is printed at all. You will have to click in the console to type your answer and end the input with Enter.

Java conditional issue

No matter what I do this piece of code will never evaluate to true when the user inputs 1 at the console... I'm confused as to why it is evaluating to false.. any help is much appreciated.
import java.io.*;
public class Default
{
public static void main(String [] args)
{
System.out.println("Welcome to the CS conversation game\n");
System.out.println("Choose your game\n1)Hex to Decimal\n2)Binary to Decimal");
Hex2Decimal PlayHex = new Hex2Decimal();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String GameSelection = null;
try
{
GameSelection = br.readLine();
}
catch (IOException ex)
{
ex.printStackTrace();
}
if(GameSelection == "1")
{
PlayHex.Play();
}
}
}
Should be "1".equals(GameSelection), == compares references of objects, while equals compares content.
Also, the Java naming convention is to start variable names in lower case. (e.g. gameSelection, playHex etc.)
You need:
if(GameSelection.equals("1"))
instead of:
if(GameSelection == "1")
== is used to check if the 2 references refer to the same object in the memory, while equals() checks whether the 2 references refer to the same object in the memory OR to 2 different objects but with the same values (the 2 strings are equivalent).
Java doesn't have operator overloading.
You will have to use .equals(...). Otherwise, you are comparing the reference address.
if(GameSelection.equals("1"))
{
PlayHex.Play();
}

Categories

Resources