Explore BrainMass
Share

Please explain the errors in the following Java code.

This content was STOLEN from BrainMass.com - View the original, and get the already-completed solution here!

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);
}
}

© BrainMass Inc. brainmass.com October 25, 2018, 4:24 am ad1c9bdddf
https://brainmass.com/computer-science/java/please-explain-the-errors-in-the-following-java-code-377926

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
See Also This Related BrainMass Solution

Java programming documentation help...

I have attached the program and I need documentation for the program. I am not good with explaining things into the code and making it look nice.

Desired documentation would clearly and effectively document including descriptions of all variables.

See attached program.

View Full Posting Details