Why if condition become false value even if the ans is hell. Is there something wrong with the program or what. I am using blueJ for java.
import java.util.Scanner;
public class QuizContest
{
Scanner value = new Scanner(System.in);
public void Contest()
{
System.out.println("Please type- hell");
String ans=value.next();
if(ans=="hell")
{
System.out.println("Congratulation. You are right");
}
else
{
System.out.println("You are wrong");
}
}
}
Comaparing string in java should be done with equals(), not ==
change:
if(ans=="hell")
to:
if(ans.equals("hell"))
When you are comparing with ==, you expect both arguments to be the exact same instance in memory. this works well with primitives, but not with objects like String
Related
can some tell me what's wrong with my code? even if I'm putting right password,unable to access balance with getBalance()... :(
package home.exercises.exceptionHandling;
import java.util.InputMismatchException;
import java.util.Scanner;
public class Manager {
private double balance = 15000.25;
public void getBalance() throws InputMismatchException {
#SuppressWarnings("resource")
Scanner s = new Scanner(System.in);
System.out.println("Enter password: ");
String password = s.nextLine();
if (password == "ManagerWantsTogetBalance") {
System.out.println("Remainning balance is " + this.balance);
} else {
System.out.println("Wrong password! Try Again..");
}
}
}
package home.exercises.exceptionHandling;
import java.util.InputMismatchException;
public class TestManager {
public static void main(String[] args) {
Manager branchManager = new Manager();
try {
branchManager.getBalance();
}
catch(InputMismatchException iex) {
System.out.println("Put password in the correct form");
}
}
}
The problem is here:
password == "ManagerWantsTogetBalance"
you should be using equals (or equalsIgnoreCase if you don't care about uppercase / lowercase differences) to compare two Strings, because those methods check the actual contents.
The == operator instead checks whether the references to the objects are equal (they point to the same memory area).
For more information: Java String.equals versus == [duplicate]
You have to compare your Strings with .equals() function, never with ==.
if("ManagerWantsTogetBalance".equals(password)){
//Code
}
When comparing String we use the .equals("Whatyouwanttocompare") method. So your if statement should look like
if(password.equals("ManagerWantsTo GetBalance")) {
}
You use == to compare primitive datatype such as int and double etc.
The == operator compares object references. So it returns true only if the operands are the same object. In the case of strings it would return true only if the objects are the same string. If you want to compare strings use the equals method. It returns true if the content of the strings is the same which is your desired behavior:
string1.equals(string2)
I created a JAVA code, and I don't have any errors, but when I run the code, the output does this:
Enter a word: Thank you for entering a word! And it does not let me enter anything, when I intend for the code to let me enter a word, then it checks if it is a word, and gives the answer if it is a word, or none if it isn't. (It is my first time asking on this site) Here's the code:
package files;
import java.util.Scanner;
public class Testprinter {
static boolean myBoolean = false;
static Scanner userInput = new Scanner(System.in);
public static void main(String[] args){
String usersInput;
while(myBoolean != true)
{
System.out.print("Enter a word: ");
usersInput = userInput.toString();
myBoolean = checkInput(usersInput);
}
checkifComplete();
}
public static boolean checkInput(String usersInput){
if(usersInput == (String)usersInput)
{
return true;
} else { return false; }
}
public static void checkifComplete(){
if(myBoolean = true){
System.out.print("Thank you for entering a word!");
}
}
}
This line is wrong:
if (usersInput == (String)usersInput)
It should be:
if (usersInput.equals(usersInput))
In Java, strings (and in general: all objects, that is all types that are non-primitive) must me compared using the equals() method, which tests for equality. The == operator is fine for testing equality between primitive types, but for objects it tests for identity - a different concept, and 99% of the time, not what you want.
And besides, you're comparing a string with itself! it'll always return true, I'm quite sure that's not what you want to do… notice that the parameter must have a different name, currently it's called just like the attribute. Perhaps this is what you meant?
public static boolean checkInput(String input) {
return usersInput.equals(input);
}
You forgot scanner.nextLine(); thats reason its not asking you enter anything.
Instead of usersInput = userInput.toString();
Use:
String usersInputStr = scanner.nextLine();
Follow this link - for how to use scanner: How can I read input from the console using the Scanner class in Java?
Your issue is using userinput.toString(), when you should be using usersInput = userInput.next();. You are currently retrieving the string representation of the scanner, not getting a word.
Corrected main:
public static void main(String[] args){
String usersInput;
while(myBoolean != true)
{
System.out.print("Enter a word: ");
usersInput = userInput.next();
myBoolean = checkInput(usersInput);
}
checkifComplete();
}
I am very new to programming and am quite young.
I have no friends/family who can help me so I am seeking help on the internet. There is problem with my code as it isn't working as I intend it.
Instead of printing out what the variable "TheChoice", it just ends.
This isn't all the code and I have consised it so that it will be easier to read and maybe more people will be able to quickly answer.
However, this is definately the part of my code which I have messed up).
public String Choices(String value1, String value2)
{
Scanner x = new Scanner(System.in);
if(x.next() == value1){return value1;}
if(x.next() == value2){return value2;}
}
// Separate class...
ChoiceClass Object1 = new ChoiceClass();
String TheChoice = Object1.Choices("Ham", "Cheese");
System.out.println(TheChoice);
There's a number of issues with your code.
Firstly, you compare Strings with == instead of equals (there's
a ton of literature about String comparison and Object equality
in Java, I suggest you take a look here and here.
Secondly, you don't always return a value in your choices method. Your method must return a String (even in its default value, as null), but you're not considering user inputs other than given arguments.
Also your Scanner next wouldn't work as you're calling it twice,
when you only want to call it once.
Finally, you should take a look at Java naming conventions: method
names are camelBack. See here for code conventions.
Here's a snippet that'll probably help you out:
public static String choices(String value1, String value2) {
Scanner x = new Scanner(System.in);
System.out.println("Type your choice and ENTER...");
String input = x.nextLine();
if (input.equals(value1)) {
return value1;
}
else if (input.equals(value2)) {
return value2;
}
// handling other user inputs
else {
return "nothing";
}
}
public static void main(String[] args) {
// usage of method. Note that you could also refactor with varargs, as in:
// String... values in method signature.
// This way you could iterate over values and check an arbitrary number of values,
// instead of only 2.
System.out.println(choices("foo", "bar"));
}
Output:
Type your choice and ENTER...
... then either "foo" or "bar" or "nothing" according to input.
You can use something similar to this:-
public String Choices(String value1, String value2)
{
Scanner x = new Scanner(System.in);
String option=x.next();
if(option!=null)
{
if(option.equals(value1)) return value1;
else if (option.equals(value2)) return value2;
}
else return option;
}
If you want to compare Strings just use equals no need to use Scanner here.
I have an assignment where my program outputs a simple String using if conditions of another String, but I keep running into a problem where I cannot create a new instance(i think that is what it is called)
anyway, here is my code
import java.util.Scanner;
public class EP54
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Do you want to continue? ");
**yesNoChecker check1 = new yesNoChecker();**
System.out.print(EP54.yesNoChecker);
}
public String yesNoChecker()
{
if(in.equalsIgnoreCase("y") ||
in.equalsIgnoreCase("yes") ||
in.equalsIgnoreCase("Sure") ||
in.equalsIgnoreCase("why not"))
System.out.println("OK");
else if(in.equalsIgnoreCase("y") ||
in.equalsIgnoreCase("yes") ||
in.equalsIgnoreCase("Sure") ||
in.equalsIgnoreCase("why not"))
System.out.println("Terminating.");
else
System.out.println("Bad Input");
}
}
Please help me! (bolded part is where I get error)
Can anybody give me a working version of the code so I can compare it with mine?
import java.util.Scanner;
public class EP54
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Do you want to continue? ");
String answer = in.next();
yesNoChecker(answer);
}
public static void yesNoChecker(String in)
{
if(in.equalsIgnoreCase("y") ||
in.equalsIgnoreCase("yes") ||
in.equalsIgnoreCase("Sure") ||
in.equalsIgnoreCase("why not"))
System.out.println("OK");
else if(in.equalsIgnoreCase("n") ||
in.equalsIgnoreCase("no") ||
in.equalsIgnoreCase("nope") ||
in.equalsIgnoreCase("quit"))
System.out.println("Terminating.");
else
System.out.println("Bad Input");;
}
}
Got it
yesNoChecker() is a function, not an object. In this case you will want to invoke yesNoChecker() (also known as "calling the method"), rather than instantiate yesNoChecker (also known as "creating an object"). Instead, your code should look something like:
import java.util.Scanner;
public class EP54
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Do you want to continue? ");
yesNoChecker();
System.out.print(EP54.yesNoChecker);
}
public String yesNoChecker()
{
// (omitted for brevity)
}
}
You instantiate new objects of a class type. For example, Scanner is a class that you've used here that Java provides you with. When you say new Scanner(), you are creating a new instance of the Scanner class.
yesNoChecker is a method, not a class-you cannot instantiate it.
You can call it:
yesNoChecker();
However, it is defined to return a String, which it currently does not do. You may want to return the string you are now printing instead.
You need to get the actual input from the user/Scanner class also.
Something like:
String s = in.nextLine();
Then you compare the String s to whatever you need ("Y", "yes" etc...)
Hope this helps!
p.s. Your function does that, but consider if someone enters a digit rather than a letter or a work. It is always a good idea to validate input before using it.
i'm new in java and have a phase of code like this:
import javax.swing.JOptionPane;
public class test
{
public static void main(String[] args) {
String value=JOptionPane.showInputDialog("please input your value");
if (value== "1"){
System.out.println("1");
}else{
System.out.println("not 1");
}
}
}
Question : why every time i put 1,system print "not 1"?
thanks alot
Try replacing value == "1" with value.equals("1"). Strings in Java are references and there are no operator overloads to help you with equality. Sometimes the strings are interned and == would work, but not usually. You should always use the equals method.