-5

I put together this program, my first one ever but after I enter the values in the boxes, the output in the end is "0" and not the subtraction. I don't know what i am missing.

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
    Can you explain why you think that you can perform the subtraction before `applesTheyNeed` and `applesTheyHave` have their values from the input? – Tom Feb 04 '17 at 10:07
  • Didn't ask that question, i'll keep that in mind next time. tks – Robert T145 Feb 04 '17 at 10:42

3 Answers3

1

Its very simple you are not calculating applesToOrder and orangesToOrder again after user input so they are taking there previous values of 0, just put these lines just above your last JOptionPane statement and see the magic.

 applesToOrder = applesTheyNeed - applesTheyHave;
 orangesToOrder = orangesTheyNeed - orangesTheyHave;
jack jay
  • 2,493
  • 1
  • 14
  • 27
0

You are doing the mat operation BEFORE the user gives the input values, move this after the JOptionPane section....

applesToOrder = applesTheyNeed - applesTheyHave;
orangesToOrder = orangesTheyNeed - orangesTheyHave;
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
0

When you do this

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

the values of applesTheyNeed, and all other variables is 0, therefore the applesToOrder is read like this

applesToOrder = applesTheyNeed - applesTheyHave

applesToOrder = 0 - 0

applesToOrder = 0

Changing the value applesTheyNeed and others afterwards , won't affect the value of applesToOrder

To fix this, simply put the statements after taking the input

Community
  • 1
  • 1
dumbPotato21
  • 5,669
  • 5
  • 21
  • 34