减法在java程序中不起作用(缺少某些东西)

时间:2017-02-04 10:02:41

标签: java subtraction

我把这个程序放在一起,我的第一个程序,但是在我输入框中的值之后,最后的输出是“0”而不是减法。我不知道我错过了什么。

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!");

3 个答案:

答案 0 :(得分:1)

非常简单,您在用户输入后不会再次计算applesToOrderorangesToOrder,因此他们将之前的值0取出,只需将这些行放在上一个{{1}之上声明并看到魔法。

JOptionPane

答案 1 :(得分:0)

在用户提供输入值之前,您正在执行mat操作, 在JOptionPane部分之后移动它......

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

答案 2 :(得分:0)

当你这样做时

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

applesTheyNeed的值,所有其他变量都是0,因此applesToOrder就像这样读取

  

applesToOrder = applesTheyNeed - applesTheyHave

     

applesToOrder = 0 - 0

     

applesToOrder = 0

之后更改了值applesTheyNeed和其他人,不会影响 applesToOrder

的值

要修复此,只需在接受输入后放置语句