Share
Explore BrainMass

Please explain the errors in the following Java code.

Please explain the errors in the following Java code.

// AverageAndSmallest
// This program will get three numbers from the user
// and determine the smallest number and the average

import java.util.Scanner; // Scanner class used for getting user input

public class AverageAndSmallest
{
// The main method that begins execution of Java application
public static void main(String args[])
{
// variable declarations
int num1; // first number to compare
int num2; // second number to compare
int num3; // third number to compare
int smallest = 0; // variable to hold smallest
double average; // variable to hold average

// create Scanner to capture input from console
Scanner input = new Scanner(System.in);

// get user input, num1 and num2
System.out.print("Enter first number: ");
num1 = input.nextInt();
System.out.print("Enter second number: ");
num2 = input.nextInt();
System.out.print("Enter third number: ");
num3 = input.nextInt();

// Compare and determine the smallest
if (num1 > num2)
smallest = num2;
if (num1 < num2)
smallest = num1;
if (num3 < smallest)
smallest = num3;

// Calculate the average
average = num1 + num2 + num3 / 3;

// Display average and the smallest
System.out.printf("Average is %.2fn", average);
System.out.printf("Smallest is %dn", smallest);
}
}

Solution Preview

There are three major bugs in the given code, as explained below.

1. Smallest number determination logic is not considering the case (num1 == num2). As a result if num1 happens to be same as num2, smallest remains as initial value 0 and thus the computation of smallest number goes wrong.

$ java AverageAndSmallest
Enter first number: 5
Enter second number: 5
Enter third number: 3
Average is 11.00
Smallest is 0

Above issue ...

Solution Summary

Solution shows the execution run for each of the errors after explaining the error. It also gives a bug-fixed version of the given code, along with the execution run for the same.

$2.19