-1

我正在尝试构建一个程序来计算四个项目的利润。这是我到目前为止的代码。我还没有做计算部分,我试图让用户选择他们想要购买的物品以及如何存储这些值。

public static void main(String[]args)
{
    int item=0;
    double price=0;
    String itemName="";
    String yes ="";
    String no="";
    String answer="";
    String response;    

    Scanner list=new Scanner(System.in);
    System.out.println( "These are the current items availabe:" ); 
    System.out.println( "Item Number\t Item Name" ); 
    System.out.println( "1)\t\t Flour\n2)\t\t Juice\n3)\t\t Crix\n4)\t\t Cereal" );
    System.out.println("Enter the item number you wish to purchase");
    item=list.nextInt();

    if( item == 1 ) 
    {
        price = 25; 
        itemName = "Flour"; 
        System.out.println( "You selected Flour" ); 
    }
    else if( item == 2 ) 
    {
        price = 15; 
        itemName = "Juice"; 
        System.out.println( "You selected Juice" ); 
    }
    else if( item == 3 ) 
    {
        price = 10; 
        itemName = "Crix"; 
        System.out.println( "You selected Crix" ); 
    }
    else if( item == 4 ) 
    {
        price = 30; 
        itemName = "Cereal"; 
        System.out.println( "You selected Cereal" ); 
    }
    else 
    {
        System.out.println( "Invalid Item Number Entered!" ); 
    }

    return;
    System.out.println("Would you like to purchase another item?");
    Scanner answer1=new Scanner(System.in);
    response=answer1.next();

    if(answer==yes)
    {
        System.out.println("Enter the item number you wish to purchase");
        item=list.nextInt();
    }
    else if(answer==no)
    {
        System.out.println("Thank you for shopping with us");
    }

问题是,我该怎么做,或者我的方法到目前为止是否准确?

对于 if else 语句,当我回答是或否时,Enter the item number you wish to purchase即使我输入否,它仍然会询问。我该如何纠正?

4

1 回答 1

2

这是不对的,在很多层面上:

String yes=""; //this is an empty string... The name does not mean anything...

....
if(answer==yes){ //comparing something with an empty string the bad way...

应该是大概

private static final String YES="yes"; //now it has content

然后

if(answer.equals(YES)) { //proper string equalitz checking
...

记住:Strings 是对象。用于.equals()比较它们的相等性。

当然也适用于该no部分。

还:

Scanner answer1=new Scanner(System.in);
response=answer1.next(); //you store the result into response

if(answer==yes){ //you check answer???

应该:

Scanner answer1=new Scanner(System.in);
response=answer1.next(); //you store the result into response

if(response.equals(YES)){ //correct check
于 2013-09-24T19:28:03.180 回答