unable to access getter properly - java

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)

Related

how do I make while loop run until a certain input is placed?

the idea is basically the loop takes in input and it runs until I type "quit" but it doesn't work the way I want to and I can't figure out why :( (p.s. im a beginner that came from python pls be kind)
import java.util.Scanner;
class HelloWorld {
static String s1;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
do {
s1 = in.next();
} while (s1 != "quit");
System.out.println(s1);
}
}
I also tried adding a temporary variable so that the while loop could check the condition before continuing but it doesn't work that way too...
import java.util.Scanner;
class HelloWorld {
static String s1;
static String s2;
static int s3;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
do {
s1=in.next();
if (s1=="quit"){
break;
}
s2=in.next();
s3=in.nextInt();
} while (s1!="quit");
System.out.println("Terminate");
}
}
Your code works fine, You just cannot use == operator to compare Strings. Use equals() or equalsIgnoreCase() method instead.
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
do {
s1 = in.next();
} while (!"quit".equals(s1)); // use equals
System.out.println(s1);
}
If You are comparing by == You are checking if both sides reference to same object. When You are using equals(), You are comparing the String values. So even if You have multiple objects with value "quit", == will return false, but equals() will return true.
You can read more here
To compare strings you have to use the .equal() or .equalsIgnoreCase() method. This should work
you can try this:
!s1.equals("quit")

Scanner library issue in java

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

How to fix a word requesting program?

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

Java, returning Strings error

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.

something about JOptionPane.showInputDialog in java

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.

Categories