//Program: NumbersGame.java
//Creating java program to find sum, difference, product and averageString dataString; // input string
import javax.swing.JOptionPane;
public class Main_Class {
// Numbers Game, a program that prompts the user for two integers and then displays their
// Sum, Difference,Product and Average.
public static void main(String[] args) {
//Obtain numerical input and calculate results
//strings entered by user
String firstInput;
String secondInput;
int input1;
int input2;
int sum;
int difference;
int product;
int average;
//read first input as string
firstInput = JOptionPane.showInputDialog("Enter first integer");
//read second input as string
secondInput = JOptionPane.showInputDialog("Enter second inter");
//converting inputs from string to integers
input1 = Integer.parseInt (firstInput);
input2 = Integer.parseInt(secondInput);
//Perform calculations
sum = input1 + input2;
difference = input1 - input2;
product = input1 * input2;
average = input1 + input2 / 2;
//display the results
JOptionPane.showMessageDialog(null,"sum = " + sum,
"Results",JOptionPane.PLAIN_MESSAGE);
JOptionPane.showMessageDialog(null,"differnce = " + difference,
"Results",JOptionPane.PLAIN_MESSAGE);
JOptionPane.showMessageDialog(null,"product = " + product,
"Results",JOptionPane.PLAIN_MESSAGE);
JOptionPane.showMessageDialog(null,"average = " + average,
"Results",JOptionPane.PLAIN_MESSAGE);
System.exit(0);
}
}
Need a little help with java program
Page 1 of 12 Replies - 300 Views - Last Post: 29 April 2010 - 02:26 PM
#1
Need a little help with java program
Posted 29 April 2010 - 02:20 PM
I am trying to find out why my program do not compute averages correct. It does all the other mathematical function correct but not averaging. Can you tell me where I went wrong with my code.
Replies To: Need a little help with java program
#2
Re: Need a little help with java program
Posted 29 April 2010 - 02:24 PM
Run some tests and show us the results. Like Input1=10, Input2=12, and the resulting average is... It might be that you need to do the addition first and then the division.
#3
Re: Need a little help with java program
Posted 29 April 2010 - 02:26 PM
as you may be familiar from math lessons, the division operator is executed before the plus operator.
so in your calculation here:
you first divide input2 by 2, and then add input1.
you should change it like so:
this way, first you perform the addition of input1 and input2, and then dividing by 2.
so in your calculation here:
average = input1 + input2 / 2;
you first divide input2 by 2, and then add input1.
you should change it like so:
average = (input1 + input2) / 2;
this way, first you perform the addition of input1 and input2, and then dividing by 2.
Page 1 of 1
|
|

New Topic/Question
Reply




MultiQuote



|