非常初学者的Java:方法无法识别传递给它的用户输入字符串



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

我正在处理一个我认为很简单的问题
基本的101购物车,带有硬编码的产品列表(仅练习问题-我知道这不是真正的做法(

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

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

硬编码字符串有效-键盘输入的字符串无效我被难住了,但我想我只是错过了一些基本的

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

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

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

依此类推

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

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

就像下一个

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

最新更新