Java conditional issue - java

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();
}

Related

Java Passing variables, avoiding toString hash

I know this has been asked before, but not in a way I understood, because I am dumb.
So.
I need to take some variables into a class, compare them against something, and then return the higher of the two. In the long run, I need to compare against a running total, but for my problem, I think the issue is considerably more fundamental. I'm not understanding how to pass a variable BACK to my main class.
import java.io.*;
public class testing123 {
public static void main(String[] args) {
InputStreamReader input = new InputStreamReader(System.in);
BufferedReader reader = new BufferedReader(input);
Integer a;
Integer b;
Integer numbersCombined;
try {
System.out.println("Please enter a number");
a = Integer.parseInt(reader.readLine());
System.out.println("Please enter a number");
b = Integer.parseInt(reader.readLine());
numbersCombined = (a + b);
testClass Check = new testClass();
System.out.println("Your numbers combined is " +numbersCombined);
System.out.println(Check);
} catch (IOException e){
System.out.println("Error reading from user");
}
}
}
class testClass {
public static Integer testClass (Integer numbersCombined) {
if (numbersCombined > 100) {
numbersCombined = numbersCombined;
}
else {
numbersCombined = 100;
}
System.out.println(numbersCombined);
return numbersCombined;
}
}
If I remove the return, this will print the numbersCombined, but that's all it does. With the return in place, it doesn't execute the print line above the return, and first prints the original numbersCombined (which it shouldn't if you use, say, 10 and 20, since that's less than 100), and then prints testClass#76046e53 rather than the actual value. I know there's a way to override it, but the answers I've found don't work for me.
I know this answer: http://www.google.com/url?q=http%3A%2F%2Fstackoverflow.com%2Fquestions%2F29140402%2Fhow-do-i-print-my-java-object-without-getting-sometype2f92e0f4&sa=D&sntz=1&usg=AFQjCNGIzxlBSH8xIS7hurKe6_Euc7B8RQ
is the basic problem I'm encountering, but the overrides listed aren't really working for me, and I want integer anyway, rather than string.
In the end, what I'm "really" doing is taking a series of 4 numbers from a user, then using this function to compare whether THIS series of numbers is higher than the previous maximum, and if it is, that's the new maximum moving forward, with a loop until the user is done entering serieses of 4 numbers, and then finally printing the maximum.
I was able to write this without ANY functions, all inline, easy as pie. But once I send the comparison to a function, I don't understand how to send it back, and I've spent all day trying to understand the concept. ALL DAY. So, while I know it's going to be a stupid answer, that's because I'm stupid, but not because I didn't try (sorry, kind of defensive. Frustrated).
Fundamentally, I want to send two (this example is just one) variables to a class, compare them, change ONE of them, and return it to the main class. In this example, I'm just trying to send ONE variable, compare it, and the send it back.
You need to call the method within TestClass. Your code is already returning an integer from that method.
Once you instantiate the class run testClass.testClass(numbers)
The way you're throwing around pseudo-global variables between classes is probably the problem. Pass them through the calls like above, rather than implicitly.
Try to do something like this:
import java.io.*;
public class HelloWorld{
public static void main(String []args){
InputStreamReader input = new InputStreamReader(System.in);
BufferedReader reader = new BufferedReader(input);
Integer a;
Integer b;
Integer numbersCombined;
try {
System.out.println("Please enter a number");
a = Integer.parseInt(reader.readLine());
System.out.println("Please enter a number");
b = Integer.parseInt(reader.readLine());
numbersCombined = (a + b);
testClass Check = new testClass(numbersCombined); // constructor should be like this
System.out.println("Your numbers combined is " + numbersCombined);
System.out.println(Check);
} catch (IOException e){
System.out.println("Error reading from user");
}
}
}
class testClass {
Integer numbersCombined;
// This is a constructor
public testClass (Integer numbersCombined) {
if (numbersCombined > 100) {
this.numbersCombined = numbersCombined; // use this to represent the object
} else {
this.numbersCombined = 100;
}
System.out.println(numbersCombined);
}
// Add method toString()
public String toString() {
return this.numbersCombined.toString();
}
}

Can `String.length()` be used to see which of two String objects is larger?

If String.length() cannot be used to compare two String objects and determine which object is larger, then what string method would do such a thing? When I run this code it terminates immediately. Is there a method to compare pairs of strings? I'm using the API for the string class as a reference here: https://docs.oracle.com/javase/6/docs/api/java/lang/String.html
public class ThingsComparer {
public static void main(String[] args) {
String ObjectOne = new String("One");
String ObjectTwo = new String("Two");
if (ObjectOne.length() > ObjectTwo.length())
{
System.out.println("ObjectOne is larger");
}
else if (ObjectOne.length() < ObjectTwo.length())
{
System.out.println("ObjectTwo is larger");
}
else if (ObjectOne.equals(ObjectTwo))
{
System.out.println("ObjectOne and ObjectTwo are equal");
}
}
}
.....
.....
else if (ObjectOne.length() == ObjectTwo.length())
{
System.out.println("ObjectOne and ObjectTwo are equal");
}
Furthermore, according to Thilo, you don't need else if (ObjectOne.length() == ObjectTwo.length()) at all specially after you have tried to look for greater and lesser than conditions. What's the 3rd condition? It's equal.
#Peanutcalota
The above code is working fine. The reason that you are not getting any output is that the 2 objects ObjectOne and ObjectTwo are having different strings and have equal lengths.
So the first and second condition will not work as both are having the same length.
The last condition will not work because both strings are different.
ObjectOne.equals(ObjectTwo) will only work if they are having same string.
And I have tried running this program, it is executing fine.
Give it a try.

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.");
}
}
}

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

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

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.

Categories

Resources