0

可能重复:
如何比较 Java 中的字符串?
Java中的字符串比较...?

我正在研究我认为是一个非常简单的问题......
带有硬编码产品列表的基本 101 购物车(仅限练习题 - 我知道这不是真正的做法)

我希望用户输入一个字符串 - 一个产品代码,然后从 Description 方法中获取相关产品的描述

它返回一个 0 值,即方法中的 if 语句似乎无法识别用户输入的字符串。

硬编码字符串有效 - 键盘输入的字符串并没有让我难过,但我认为我只是错过了一些基本的东西

import java.util.*;

class CW1ShoppingCart1_2ShowProdAndGetChoice
{
public static void main(String[] args)

{
/*PART 1 Offer catalogue and get user choice*/

System.out.println("ITEMS AVAIALBLE TODAY: \n");
System.out.print("P4383"+ "\t"+ CW1ShoppingCart1GetProductDetails.Description("P4383"));
System.out.println("\t"+ "$"+ CW1ShoppingCart1GetProductDetails.Price("P4383"));
System.out.print("P4385"+ "\t"+ CW1ShoppingCart1GetProductDetails.Description("P4385"));
System.out.println("\t"+ "$"+ CW1ShoppingCart1GetProductDetails.Price("P4385"));
System.out.print("P4387"+ "\t"+ CW1ShoppingCart1GetProductDetails.Description("P4387"));
System.out.println("\t"+ "$"+ CW1ShoppingCart1GetProductDetails.Price("P4387"));
System.out.println("\nTO START SHOPPING ENTER A PRODUCT CODE AND HIT RETURN \n");

Scanner in = new Scanner (System.in);
String ProdCode =in.nextLine();

System.out.println("You Chose: "+ CW1ShoppingCart1GetProductDetails.Description(ProdCode));

}
}

class CW1ShoppingCart1GetProductDetails
{

static String Description(String ProdCode)
{

String Proddesc;

if(ProdCode=="P4387")Proddesc = "Little used helper monkey - 1 ";
else if(ProdCode=="P4385") Proddesc = "Chilli chocolate - 100g ";
else if(ProdCode=="P4383")  Proddesc = "State-owned Bank - real value - 1 entity ";
else Proddesc = "0";

return Proddesc;
}

static double Price(String ProdCode)
{

double ProdPrice;

if(ProdCode=="P4387")  ProdPrice = 1200;
else if(ProdCode=="P4385") ProdPrice = 3.27;
else if(ProdCode=="P4383")  ProdPrice = -0.08;
else ProdPrice = 0;

return ProdPrice;
}

} 
4

3 回答 3

10

问题是您正在使用==比较字符串。改为使用equals

if(ProdCode.equals("P4387"))Proddesc = "Little used helper monkey - 1 ";

等等

于 2013-01-13T09:28:16.900 回答
0

不要使用 == 来比较字符串。有时您也可能使用 '==' 得到正确的结果,但这是由于字符串池中存在相同的字符串。始终使用 String 类中可用的 equals 方法来比较字符串

于 2013-01-13T09:35:05.340 回答
0

作为替代解决方案,您可以使用枚举

像下一个

public enum ShoppingCart {
    P4387(1200, "Little used helper monkey - 1 "),
    P4385(3.27, "Chilli chocolate - 100g "),
    P4383(-0.08, "State-owned Bank - real value - 1 entity ");

    private final double price;
    private final String description;

    private ShoppingCart(double price, String description) {
        this.price = price;
        this.description = description;
    }

    public double getPrice() {
        return price;
    }

    public String getDescription() {
        return description;
    }
}

使用类似的东西:

System.out.printf("Shopping card with name %s have price = %f and description %s",
        currentShoppingCart.name(),
        currentShoppingCart.getPrice(),
        currentShoppingCart.getDescription());
于 2013-01-13T09:47:58.287 回答