...

View Full Version : Help, I'm Confused



InsTanCeZ
02-08-2012, 07:07 AM
Write a program named Median.java that asks the user for three integers and outputs the median.
I have to do this using if else statements. It seems really easy, but I can't figure it out. Help!

Here's my code:

import java.util.*;

public class Median {

public static void main(String[] args) {

Scanner console = new Scanner(System.in);

System.out.println("Please enter number 1");
int max = console.nextInt();
int min = max;
int median = min;

for (int i=2; i <= 3; i++) {
System.out.println("Please enter number "+i);
int enteredNumber = console.nextInt();
if (enteredNumber > max) {
max = enteredNumber;
}
else {
enteredNumber = median;
}
if (enteredNumber < min) {
min = enteredNumber;
}
else {
enteredNumber = median;
}
}
System.out.println("The median is: "+median);
}
}

When I run this it just gives me back the first number I entered.

Fou-Lu
02-08-2012, 02:43 PM
The logic is half right, but you are overwriting the enteredNumber with that of the median which is backwards. Its easier than this though, with only 3 numbers:


if (enteredNumber > max)
{
median = max;
max = enteredNumber;
}
else if (enteredNumber < min)
{
median = min;
min = enteredNumber;
}
else
{
median = enteredNumber;
}

If you can't use if/elseif, then the logic of if/elseif/else is identical to if/else(if/else).

Also, in the future please select a title that better describes the issue you are having.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum