2013-09-24 61 views
-1

我想建立一個計算,將計算爲四項items.the是利潤的代碼我到目前爲止。我還沒有做計算部分,即時嘗試讓用戶選擇他們想要購買什麼項目以及如何存儲這些值。在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語句,當我回答yes或no時,即使我輸入no也要求Enter the item number you wish to purchase。我如何糾正這一點?

回答

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 s爲對象。使用.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 
+0

側問題:請問在這種情況下,編譯器,用 「是」 代替YES?而不是在運行時檢查變量? – Cruncher

+0

編譯器應該將yes替換爲yes。 – SamYonnou

+0

@Cruncher與靜態最終修飾符,我絕對認爲它應該... – ppeterka