Java assignment 05: Write the largest integer

  Quizzes     Assignments     Puzzles     Easy exercises     Required knowledge  
Java Assignments   Green = Easy,  Blue = Normal,  Red = Hard
Select    01   02   03   04   05   06   07   08   09   10   By title 

Write the body of the method getLargest. The method writes the largest number out of three integers. If two or more equal largest integers are passed to the method, the output of the program should be “Enter unique numbers!”.

 

Java assignment 5: Write the largest integer

Level: Normal

import java.util.Scanner;

public class Math
{
  void getLargest(int i, int i2, int i3)
  {
    // add the body of the method here!
  }
  public static void main(String[] args)
  {
    Scanner input = new Scanner(System.in);
    System.out.print("Enter the first nr: ");
    int i = input.nextInt();
    System.out.print("Enter the second nr: ");
    int i2 = input.nextInt();
    System.out.print("Enter the third nr: ");
    int i3 = input.nextInt();
    Math math = new Math();
    math.getLargest(i, i2, i3);
    input.close();
  }
}
/*
In the following example the user enters 34, 55 and 2
Enter the first nr: 34
Enter the second nr: 55
Enter the third nr: 2
55
*/
 Author: Sar Maroof

Answer explanation

The body of the method is written in the following code.

This program asks the user to enter three numbers respectively and then the program calculates the largest number.

import java.util.Scanner;

public class Math
{
  void getLargest(int i, int i2, int i3)
  {
    if(i > i2 && i > i3)
      System.out.println(i);
    else if(i2 > i && i2 > i3)
      System.out.println(i2);
    else if(i3 > i && i3 > i2)
      System.out.println(i3);
    else System.out.println(""
        + "Enter unique numbers!");
  }
  public static void main(String[] args)
  {
    Scanner input = new Scanner(System.in);
    System.out.print("Enter the first nr: ");
    int i = input.nextInt();
    System.out.print("Enter the second nr: ");
    int i2 = input.nextInt();
    System.out.print("Enter the third nr: ");
    int i3 = input.nextInt();
    Math math = new Math();
    math.getLargest(i, i2, i3);
    input.close();
  }
}





Sar Maroof is a professional software development teacher, gives master classes and publishes technical articles. He is also an expert software developer and worked for several big as well as small companies and later as a freelancer.

 Subscribe to Sar Maroof's RSS feeds!
 Mail this page to a friend!
 Bookmark this page!

Leave a Reply

Your email address will not be published. Required fields are marked *