2014-02-15 36 views
1

你好,我試圖讓+ =來增加平衡值。我現在明白,在Java腳本中使用+ =是通過引用傳遞的,但是我怎樣才能使用它來傳遞值。加上等於操作員錯誤

alert("Welcome to the Online Bank Teller"); 

     var balance = 100.00; 
     var amount; 
     var run = true; 

     do{ 

      var pick = prompt("Make a selection...\n1-Check Balance, 2-Deposit, 3-Withdraw, 4-Quit"); 

      if(pick == 1){alert("Your balance is: $" + balance.toFixed(2));} 
      else if(pick == 2){ 
        amount = prompt("Enter the amount you want to deposit: $"); 

        if(amount > 1000){alert("You can only enter up to $1000 per deposit!");} 
     Right here--->balance += amount; 
        alert("Your new balance: $" + balance.toFixed(2)); 
      } 
      else if(pick == 3){ 
        amount = prompt("Enter the amount you want to withdraw: $"); 

        if(amount > balance){alert("Amount exceeded account balance!");} 
        else if(amount > 500){alert("The max you can take out is up to $500 per withdraw!");} 
        else if (amount <= balance){ 
          balance -= amount; 
          alert("Your new balance: $" + balance.toFixed(2)); 
        }        
      } 
      else if(pick == 4){run = false;} 
      else{alert("Not a valid choice!");} 

     }while(run) 

當用戶輸入新的存款時,我如何獲得它以更改變量內部的值。

我得到

Your balance is: $10022 

,而不是

Your balance is: $122 

在此先感謝...

+0

Whay是否被標記爲'java'? –

回答

1

使用parseInt()函數,以輸出從提示

amount = parseInt(prompt("Enter the amount you want to deposit: $"), 10); 

DEMO

+0

歡迎您:) –

0

添加一個字符串到一些與+=運營商產生一個字符串。

prompt()返回一個字符串,因此你需要將返回值轉換爲數字:

balance += +amount; 

或者使用parseFloat()轉換數值。雖然我無法理解你將如何得到任何提醒,因爲字符串沒有toFixed()方法,因此代碼中的alert()應該會觸發錯誤。

0

獲取每個量嘗試

balance = parseInt(balance) += parseInt(amount); 

餘額和量都是字符串,因此,例如:

添加字符串'50'到stri的「3」 NG竟被使「503」

添加「50」的浮點值的「3」的浮點值將使「53」

0

至於parseInt功能的替代方案,已經被所提到的,也有一些「快速&髒」的方式來做到這一點:

amount = 1 * prompt("Enter the amount you want to deposit: $"); 
// get'S converted because * is only defined on numbers 

amount = +prompt("Enter the amount you want to deposit: $"); 
// converted because unary + is only defined on numbers 

和一些其他不太常見的。