String input and if [duplicate] - java

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 6 years ago.
public class LabWork {
private String yourStatus;
private int yourIncome;
private double tax;
public int calculateTax () {
if (yourStatus = "Married" && yourIncome <= 2000) {
tax = yourIncome/10;
}
else if (yourStatus = "Married" && yourIncome > 2000) {
tax = 3*yourIncome/20;
}
else if (yourStatus = "Single" && yourIncome <=2000) {
tax = 17*yourIncome/100;
}
else
tax = 22*yourIncome/100;
}
public double getTax () {
return tax;
}
}
this is my first code and I have a tester class to use this like:
import java.util.Scanner;
public class UseLab3Work {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("What is your status? ");
String yourStatus = keyboard.next();
System.out.println("What is your incomew? ");
int yourIncome = keyboard.nextInt();
}
}
However, in the first program, I'm getting an error like "String cannot be converted to boolean" at line 7,10 and 14. Then how should I use if with String? For example I have input in tester and when I write there Married, the program should calculate tax related to my String input.

I first would have thought to mark this a duplicate, since you are comparing your Objects wrong, but it's a step further.
if (yourStatus = "Married" )
Here, you don't compare the values of the String, you actually just assign it.
if (yourStatus == "Married")
This would be better, but will produce false results. After all, the == operator is used for referential comparison, while you want to compare values.
if (yourStatus.equals("Married")) (or if (yourStatus.equalsIgnoreCase("Married")) )
would be better, since this is the correct way to compare the values of Strings.
An even better way would be:
if ( "Married".equals(yourStatus))
In the other order, if yourStatus is null, it will throw a NullPointerException, which you avoid by calling equals (or equalsIgnoreCase) on the String literal.

Related

Program not noticing when the string is equal to a specific string [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 6 years ago.
I've been trying to create a program that censors a word but I was having difficulty with that so I tried going back to some of the fundamental code and testing it and I am coming across an odd result.
import java.util.Scanner;
public class TextCensor
{
public static void main(String[] args)
{
String input;
Scanner keyboard = new Scanner(System.in);
input = keyboard.nextLine();
int length = input.length() - 1;
if (length + 1 >= 3)
{
for (int i=0; i<(length - 1); i=i+1 )
{
char first = input.charAt(i);
char second = input.charAt(i+1);
char third = input.charAt(i+2);
String censorCheck = "" + first + second + third;
if (censorCheck == "tag")
{
System.out.println("success");
}
else
{
System.out.println(censorCheck);
}
}
}
else
{
System.out.println(input);
}
}
}
If I input the string "adtag" I will obtain the following output:
adt
dta
tag
yet "success" will never be printed despite the fact that I have printed a censorCheck that is equal to "tag".
String is an object. You have to compare objects by equals():
censorCheck.equalsIgnoreCase("tag")
Ignore case works fir upper letters as well.
Only for primitives you can use comparison by ==:
3 == 3
You are trying to check whether both instance of String is same or not instead of checking contents of both string.
You should try censorCheck.equals("tag") .
To compare whether contents of two string are equal or not in JAVA you should use the equals() method. You cannot compare the value of two string by the == operator . In your case use if (censorCheck.equals("tag")) and see if you get the desired result.

IF condition on strings [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
I'm writing a simple code to test the value that was inputted to my constant value.
I declared this code as my constant value.
String LetMeThrough = "drunk";
String GotAnID = "drunk";
This is the whole code.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner DrunkTest = new Scanner(System.in);
String InputDrunk;
String InputDrunkAgain;
String LetMeThrough = "drunk";
String GotAnID = "drunk";
System.out.print("Type drunk: ");
InputDrunk= DrunkTest.next();
System.out.print("Re Type drunk: ");
InputDrunkAgain = DrunkTest.next();
if(InputDrunk == LetMeThrough & InputDrunkAgain == GotAnID){
System.out.print("You're not DRUNK");
}
else
System.out.print("You're F***** DRUNK");
}}
The problem is that if I type "drunk" on both.
I will get "You're F****** DRUNK" instead of the "You're not DRUNK".
When the inputted values is the same as my constant values.
You must use String::equals method to compare.

How do i save next string in scanner? [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
Iam making a basic calculator with 3 functions. Iam using a Scanner-utility to help me interact with the calculator. You enter the first number, then it saves it to a variable, You enter a second number and that is also saved to a variable. Then after that it asks you what you want to do with the numbers. You can choose between Multiply, Add, Subtract. But none of them seem to work, and i dont know why, but iam guessing that the String that is inserted after the question isnt saved or maybe iam using wrong method.
import java.util.Scanner;
public class MainClass {
private static final String Multiply = null;
private static final String Add = null;
private static final String Subtract = null;
public static void main(String[] args)
{
MainClass mainObject=new MainClass();
mainObject.Calculator();
}
public void Calculator()
{
double firstnumber;
double secondnumber;
double result;
String word1="Multiply";
String word2="Add";
String word3="Subtract";
Scanner scan=new Scanner(System.in);
System.out.println("Enter first number");
firstnumber=scan.nextInt();
System.out.println("Enter second number");
secondnumber=scan.nextInt();
System.out.println("What do you want to do?");
String operator=scan.next();
if(operator==word1)
{
result=firstnumber*secondnumber;
System.out.println(result);
}
else if(operator==word2)
{
result=firstnumber+secondnumber;
System.out.println(result);
}
else if(operator==word3)
{
result=firstnumber-secondnumber;
System.out.println(result);
}
}
}
The comparison operation between the strings is not == but the equals() method:
if(operator.equals("add"))
...
else if (operator.equals("subtract"))
...
else if (operator.equals("multiply"))
...
else
wrong input

How can I store local variables into class variables in java? [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
I'm writing a interactive application in Java and one of my local variables isn't adding itself into the class variable which is screwing up my final output.
Here is the class variable public static double deduction;
Here is what I'm trying to store into it
System.out.println("Do you want medical insurance?");
String choice = kb.nextLine();
if (choice == "yes")
{
medIns = 32.50;
}
else
{
medIns = 0;
}
System.out.println("Do you want dental insurance?");
choice = kb.nextLine();
if (choice == "yes")
{
dentIns = 20.00;
}
else
{
dentIns = 0;
}
System.out.println("Do you want long-term disability insurance?");
choice = kb.nextLine();
if (choice == "yes")
{
lifeIns = 10.00;
}
else
{
lifeIns = 0;
}
deduction = medIns + dentIns + lifeIns;
return deduction;`
Here is what it's finally going into totalpay = gross + (gross * retire) - deduction;
When I put in all the other input it's not storing the local deduction into the class deduction so it can be processed into my totalpay calculation.
Your if/else statements are always false!
deduction = medIns + dentIns + lifeIns; is always deduction = 0 + 0 + 0; no matter what the inputs are given your mis-use of the == operator.
== vs .equals() vs .equalsIgnoreCase()
choice == "yes" is not how you compare Strings in Java, in your case this will never be true.
== compares identity ( is the left hand side the exact same object instance as the right hand side ), .equals() and .equalsIgnoreCase() is how you compare contents of String objects in Java.
Idiomatic Solution
In your case the correct approach is "yes".equalsIgnoreCase(choice.trim()) putting the literal first avoids having to check for null.
a more comprehensive solution would to match on a regular expression
choice.matches("(?i)^y.*") which would match anything that starts with a y and has zero or more characters regardless of case, given that choice isn't null.

Java If loop don't get executed: Scanner [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
My second scanner input get stored as desired but still the if condition comparing correctString == stringValue is not executed.
Could you help.
{
static String stringValue = "A";
public static void main(String[] args) {
int time;
time = speedType();
//System.out.println(time);
}
private static int speedType() {
System.out.println("Let's play a game\nHow fast can you type \"I type very quickly\" \nPress Enter then type the statement and then press Enter again");
Scanner scanner = new Scanner (System.in);
String string = scanner.nextLine();
if(string.equals("")){
Date startTime = new Date();
System.out.println("Start:\n");
String correctString = scanner.nextLine();
System.out.println(correctString);
if (correctString == stringValue){
Date endTime = new Date();
System.out.println(endTime);
}
else
System.out.println("Please enter correct string");
}
return 0;
}}
Regarding,
if (correctString == stringValue){
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 right now. 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
}

Categories

Resources