Question

I've been working on a solution of a problem in Java. I have a store and I need to ask the customer if she/he had bought anything. If he/she types "yes" I want the program to continue to the next question and if he/she types "no" I want a message to appears such as "have a nice day!" and then I want the program to stop. How can I manage this?

Thank you!

Here's what I've done so far ~Line 17 to 20~ (but it doesn't work very well):

import java.util.Scanner;

public class Discount {

public static void main(String[] args) {
    String cname;
    float I_price, drate, discount, dprice;

    Scanner in = new Scanner(System.in);

    System.out.println("Enter Costumers Name:");
    cname = in.next();

    System.out.println("Have you bought anything?");
    if (cname == "no") {
        System.out.println("Have a good day!");
        System.exit(0);
    }

    System.out.println("Enter Price of Item:");
    I_price = in.nextFloat();

    System.out.println("Enter Discount Rate:");
    drate = in.nextFloat();

    discount = (I_price * drate / 100);
    dprice = (I_price - discount);

    System.out.println(
            "Costumer Name:" + cname + "\n" + "Discount Rate:" + discount + "\n" + "Discounted Price:" + dprice + "\n");
    }
}
Was it helpful?

Solution

replace if(cname=="no"){ with if(cname.equals("no")){

While comparing 2 Strings use String#equals() instead of ==

OTHER TIPS

Compare String with equals() method not ==. you should change it to

if(cname.equals("no")){

== will do a conditional equality test on the values of right and left operand. This should be used only for comparing primitive types like int, float etc. This should not be used since the object reference values will point to the memory address and they will not be same. There is also a concept called String Constant Pool. When you create the String using assignment operator instead of new like

String name ="StackOverFlow";

then, it will pass the equality test using if(name == "StackOverFlow") Since the memory address would be same for equal String values in constant pool. In this case, usage of == works. i.e compile time constants

Generally, use equals() to test the equality of the object. The equals() method of String Class compares the actual values (i.e characters) in the String literal instead of their memory address. So, In Java, Strings should be compared using equals() method only!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top