Java中的利润计算器

时间:2013-09-24 19:14:56

标签: java

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

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语句,当我回答是或否时,即使我输入no,它仍会询问Enter the item number you wish to purchase。我该如何纠正这个?

1 个答案:

答案 0 :(得分: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
...

请记住:String是对象。使用.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