1 Replies - 3109 Views - Last Post: 07 April 2011 - 10:04 PM Rate Topic: -----

#1 AhmerjavedC++  Icon User is offline

  • D.I.C Regular

Reputation: 0
  • View blog
  • Posts: 253
  • Joined: 02-October 09

Logical Error in program.. Program finds middle number of 3 numbers

Posted 07 April 2011 - 08:30 PM

Assignment: Write a method called middle() which, when given three integers, displays the one that has a value in between the other two. So, middle(1, 2, 3) causes 2 to be displayed, and middle (5, 6, 5) causes 5 to be displayed. Write a main program with a loop in it; each time through the loop, the user is asked to enter three integers; the main program then calls middle() with the three integers and middle() displays the one with the middle value. After you get the program working, rename the source code file to “CS1_Name_X9_3”, where Name is your last name.

Question: What is wrong with my code that it is not working properly?.. When i enter 5 6 5 my output value is 0 but 1 2 3 works fine.

import java.util.Scanner;
public class CS1_Javed_X9_3
{
 public static void main(String[] args)//main part of the program receives input from user for 3 numbers
 {
  int h1, h2, h3;
  Scanner keyboard = new Scanner(System.in);
  while (true)
  {
   System.out.println("Please enter 3 numbers: ");
   h1 = keyboard.nextInt();
   h2 = keyboard.nextInt();
   h3 = keyboard.nextInt();
   middle(h1, h2, h3); // Call to method Middle 
  }

 }

 static void middle(int n1,int n2,int n3) //int n1, n2 and n3 are private variables belonging to method middle 
 {
  int nMiddle = 0;

  if (n2 < n1 && n1 < n3)//This series of if statements will find the middle number
   nMiddle = n1;
  if (n1 < n2 && n2 < n3)
   nMiddle = n2;
  if (n1 < n3 && n3 < n2)
   nMiddle = n3;
  if (n3 < n1 && n1 < n2)
   nMiddle = n1;
  if (n3 < n2 && n2 < n1)
   nMiddle = n2;
  if (n2 < n3 && n3 < n1)
   nMiddle = n3;

  System.out.println("The middle value is: " + nMiddle);
 }
}



Is This A Good Question/Topic? 0
  • +

Replies To: Logical Error in program.. Program finds middle number of 3 numbers

#2 GregBrannon  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2205
  • View blog
  • Posts: 5,239
  • Joined: 10-September 10

Re: Logical Error in program.. Program finds middle number of 3 numbers

Posted 07 April 2011 - 10:04 PM

Your method initializes nMiddle to 0. You might find a more straightforward solution by initializing nMiddle to one of the 3 variables.

Then your method doesn't account for the case when 2 or more of the 3 variables are the same. Since there is no requirement for the variables to be different, your method must include solutions for those cases. What will your current algorithm do when all 3 numbers are the same?
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1