2017-02-04 68 views
-5

我把這個程序,我的第一個有史以來,但我輸入框中的值後,輸出在最後是「0」,而不是減法。我不知道我錯過了什麼。減法不工作在Java程序(缺少的東西)

import java.util.Scanner; 
import javax.swing.JOptionPane; 
public class PSEUDOCODE_PROGRAM { 

public static void main(String[] args) { 
    Scanner scnr= new Scanner(System.in); 

    String applesHad = " "; 
    String applesNeed = " "; 
    String orangesHad = " "; 
    String orangesNeed = " "; 
    int applesTheyHave = 0; 
    int applesTheyNeed = 0; 
    int orangesTheyHave = 0; 
    int orangesTheyNeed = 0; 
    int applesToOrder = 0; 
    int orangesToOrder = 0; 
    applesToOrder = applesTheyNeed - applesTheyHave; 
    orangesToOrder = orangesTheyNeed - orangesTheyHave; 

//Ask produce buyer how many apples are in stock 
applesHad= JOptionPane.showInputDialog(null, "How many apples do you have: "); 
applesTheyHave = Integer.parseInt(applesHad); 
applesHad= JOptionPane.showInputDialog(null, "How many apples do you need: "); 
applesTheyNeed = Integer.parseInt(applesHad); 
//Ask produce buyer how many oranges are in stock 
orangesHad= JOptionPane.showInputDialog(null, "How many oranges do you have:  "); 
orangesTheyHave = Integer.parseInt(orangesHad); 
orangesHad= JOptionPane.showInputDialog(null, "How many oranges do you need: "); 
orangesTheyNeed = Integer.parseInt(orangesHad); 
JOptionPane.showMessageDialog(null, "You must order " + applesToOrder + "   apples and " + orangesToOrder + " oranges!"); 
+2

你能解釋後的聲明,爲什麼你認爲你可以執行前'applesTheyNeed'和'applesTheyHave'有從輸入它們的值相減? – Tom

+0

沒有問這個問題,下次我會記住這一點。 tks –

回答

1

它非常簡單,你沒有用戶輸入後再次計算applesToOrderorangesToOrder所以他們正在那裏以前的0值,只是把這些線正上方你最後JOptionPane發言,看到了魔術。

applesToOrder = applesTheyNeed - applesTheyHave; 
orangesToOrder = orangesTheyNeed - orangesTheyHave; 
+0

太好了。把所有東西放在一起時忽略了細節。我會記得下一次。 tks –

+0

@ RobertT145 thnks。 [閱讀此](http://stackoverflow.com/help/someone-answers) –

0

之前,用戶給出的輸入值, 的JOptionPane的部分後,移動這個你正在做墊操作....

applesToOrder = applesTheyNeed - applesTheyHave; 
orangesToOrder = orangesTheyNeed - orangesTheyHave; 
0

當你做到這一點

applesToOrder = applesTheyNeed - applesTheyHave; 
orangesToOrder = orangesTheyNeed - orangesTheyHave; 

applesTheyNeed和所有其他變量的值是0,因此applesToOrder是這樣讀取的

applesToOrder = applesTheyNeed - applesTheyHave

applesToOrder = 0 - 0

applesToOrder = 0

更改值applesTheyNeed和其他人之後,不會影響applesToOrder

到fi X此,只需放取輸入

+0

我錯過了。下次會記得。謝謝 –

相關問題