Java Highest and Lowest Number from a Set Application

Chris7S

Nerd by definition, programmer by trade
Messages
1,522
Reaction score
490
I was approached by another student again yesterday that is taking a Java course and he asked how to determine the highest and lowest number in a set array. Since I have already taken a few Java courses and taught myself most of the language I decided to help him out and write him a snippet of code. So whenever a fellow student comes to me for help I will release it here on Se7ensins because I noticed some of the developers here are starting college and they will need to know some of this basic knowledge. I hope this helps someone out in the log run because I know small applications like this really helped me when learning how to code. Enjoy!

Java:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package lowest.and.highest.number;
import java.util.*;

/**
*
* @author Chris
*/
public class LowestAndHighestNumber {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args)
    {
        int num1;
        int num2;
        int num3;
        int num4;
        int num5;
    
        Scanner userInput = new Scanner(System.in);
        System.out.println("Please enter a set of numbers (Max - 5 Numbers):");
        num1 = userInput.nextInt();
        num2 = userInput.nextInt();
        num3 = userInput.nextInt();
        num4 = userInput.nextInt();
        num5 = userInput.nextInt();
    
        int numbers[] = {num1, num2, num3, num4, num5};
        int largestNumber = numbers[0];
        int smallestNumber = numbers[0];
    
        for(int i = 0; i < numbers.length; i++)
        {
            if(numbers[i] > largestNumber)
            {
                largestNumber = numbers[i];
            }
        
            if (numbers[i] < smallestNumber)
            {
                smallestNumber = numbers[i];
            }
        }

        System.out.println("The largest number in the set {" + num1 + ", " + num2 + ", " + num3 + ", " + num4 + ", " + num5 + "} is " + largestNumber);
        System.out.println("The smallest number in the set {" + num1 + ", " + num2 + ", " + num3 + ", " + num4 + ", " + num5 + "} is " + smallestNumber);
    }

}
And here is the output of the application:
 
Last edited:

Drgstr420

Enthusiast
Messages
517
Reaction score
63
For those beginners that might see this post, yes, his code may help you. But his code is not "clean" code by any means. I would search elsewhere for better practices.
 

Drgstr420

Enthusiast
Messages
517
Reaction score
63
Can you please explain how this code isnt 'clean' ?
The simplicity of the application allows the entire thing to be written in the main method. This would not be the case in a real world app. Nonetheless, I'll also write mine in the main method. If you would like me to show you how to do it otherwise, just ask.

Also, there are multiple ways to fix up his code. I'll show you two ways. The first just cleans up his sloppy code. The second implements a better design.

Cleaned up code, same design:
Code:
package demo;

import java.util.Scanner;

public class CleanerCode {

    /* The size of the set */
    private static final int SETSIZE = 5;

    /******************************************************************
     * Gets the highest and lowest numbers from a set
     *
     * @param args
     *****************************************************************/
    public static void main(String[] args){
        String set = "";
        int numbers[] = new int[SETSIZE];
        Scanner userInput = new Scanner(System.in);
      
        System.out.println("Please enter a set of numbers (Max - 5 Numbers):");
        for(int i = 0; i < SETSIZE; i++){
            int tempNum = userInput.nextInt();
            numbers[i] = tempNum;
            set += numbers[i] + " ";
        }
        userInput.close();

        int largestNumber = numbers[0];
        int smallestNumber = numbers[0];
        for(int i = 0; i < numbers.length; i++){
            if(numbers[i] > largestNumber){
                largestNumber = numbers[i];
            }
            if (numbers[i] < smallestNumber){
                smallestNumber = numbers[i];
            }
        }
        System.out.println("The largest number in the set { " + set + "} is " + largestNumber);
        System.out.println("The smallest number in the set { " + set + "} is " + smallestNumber);
    }
}
Changes:
-Not a ton of variables used.
-Closes scanner
-Better print statement
-Global variable for set size


Better design:
Code:
package demo;

import java.util.Scanner;
import java.util.SortedSet;
import java.util.TreeSet;

public class SortedSetDemo {
  
    private static final int SETSIZE = 5;

    public static void main(String[] args){
        SortedSet<Integer> numbers = new TreeSet<Integer>();
      
        Scanner userInput = new Scanner(System.in);
        System.out.println("Please enter a set of numbers (Max - 5 Numbers):");
        for(int i = 0; i < SETSIZE; i++){
            int tempNum = userInput.nextInt();
            numbers.add(tempNum);
        }
        userInput.close();
      
        System.out.println("The largest number in the set " + numbers.toString() + " is " + numbers.last());
        System.out.println("The smallest number in the set " + numbers.toString() + " is " + numbers.first());

    }
}
Changes:
-Uses SortedSet to keep inputs in a set of numbers automatically sorted
-Does not need to keep a string of numbers in the set, it is already done by SortedSet
-More compact and concise code
 

Chris7S

Nerd by definition, programmer by trade
Messages
1,522
Reaction score
490
For those beginners that might see this post, yes, his code may help you. But his code is not "clean" code by any means. I would search elsewhere for better practices.
This program is meant to teach logic rather than being as concise as possible. I could not use what I wanted to use because the class had only went over some of the more simple concepts.
 

Im4eversmart

The hacks are real
Messages
2,163
Reaction score
1,903
The simplicity of the application allows the entire thing to be written in the main method. This would not be the case in a real world app. Nonetheless, I'll also write mine in the main method. If you would like me to show you how to do it otherwise, just ask.

Also, there are multiple ways to fix up his code. I'll show you two ways. The first just cleans up his sloppy code. The second implements a better design.

Cleaned up code, same design:
Code:
package demo;

import java.util.Scanner;

public class CleanerCode {

    /* The size of the set */
    private static final int SETSIZE = 5;

    /******************************************************************
     * Gets the highest and lowest numbers from a set
     *
     * @param args
     *****************************************************************/
    public static void main(String[] args){
        String set = "";
        int numbers[] = new int[SETSIZE];
        Scanner userInput = new Scanner(System.in);
     
        System.out.println("Please enter a set of numbers (Max - 5 Numbers):");
        for(int i = 0; i < SETSIZE; i++){
            int tempNum = userInput.nextInt();
            numbers[i] = tempNum;
            set += numbers[i] + " ";
        }
        userInput.close();

        int largestNumber = numbers[0];
        int smallestNumber = numbers[0];
        for(int i = 0; i < numbers.length; i++){
            if(numbers[i] > largestNumber){
                largestNumber = numbers[i];
            }
            if (numbers[i] < smallestNumber){
                smallestNumber = numbers[i];
            }
        }
        System.out.println("The largest number in the set { " + set + "} is " + largestNumber);
        System.out.println("The smallest number in the set { " + set + "} is " + smallestNumber);
    }
}
Changes:
-Not a ton of variables used.
-Closes scanner
-Better print statement
-Global variable for set size


Better design:
Code:
package demo;

import java.util.Scanner;
import java.util.SortedSet;
import java.util.TreeSet;

public class SortedSetDemo {
 
    private static final int SETSIZE = 5;

    public static void main(String[] args){
        SortedSet<Integer> numbers = new TreeSet<Integer>();
     
        Scanner userInput = new Scanner(System.in);
        System.out.println("Please enter a set of numbers (Max - 5 Numbers):");
        for(int i = 0; i < SETSIZE; i++){
            int tempNum = userInput.nextInt();
            numbers.add(tempNum);
        }
        userInput.close();
     
        System.out.println("The largest number in the set " + numbers.toString() + " is " + numbers.last());
        System.out.println("The smallest number in the set " + numbers.toString() + " is " + numbers.first());

    }
}
Changes:
-Uses SortedSet to keep inputs in a set of numbers automatically sorted
-Does not need to keep a string of numbers in the set, it is already done by SortedSet
-More compact and concise code
Or use streams and do it in 3 lines.
 

YYes

Enthusiast
Messages
177
Reaction score
52
Or use streams and do it in 3 lines.
I wanna see this. I'm going to take a stab at it.

Edit:
Here's some inherently clean code. It splits the three main tasks (getting the input, finding the highest, and finding the lowest number) into three different functions.
C#:
using System;
namespace Challenge
{
    class HiLo
    {
        public static void Main(String[] args)
        {
            Console.WriteLine("Enter numbers, end with blank line.");

            int[] numbers = GetNumbers();
            Console.WriteLine("Highest number: " + Highest(numbers));
            Console.WriteLine("Lowest number: "  + Lowest(numbers));
        }

        private static int[] GetNumbers()
        {
            // this would be easier with System.Collections.Generic,
            // but the following translates easily into C (int *ret = malloc(sizeof(int) * size))
            string[] buf = new string[1000];
            int size = 0;

            while ((buf[size++] = Console.ReadLine()) != "")
            { //error handling could go here
            }
            size--;

            int[] retbuf = new int[size];
            for (int i = 0; i < size; ++i)
            {
                // or here
                retbuf[i] = int.Parse(buf[i]);
            }
            return retbuf;
        }

        private static int Highest(int[] nums)
        {
            int highest = int.MinValue;

            for (int i = 0; i < nums.Length; i++)
                highest = highest > nums[i] ? highest : nums[i];

            return highest;
        }

        public static int Lowest(int[] nums)
        {
            int lowest = int.MaxValue;

            for (int i = 0; i < nums.Length; i++)
                lowest = lowest < nums[i] ? lowest : nums[i];

            return lowest;
        }
    }
}
 
Last edited:

Im4eversmart

The hacks are real
Messages
2,163
Reaction score
1,903
I wanna see this. I'm going to take a stab at it.
Code:
List<Integer> nums = Arrays.asList(3,7,1,3,2,9);
System.out.printf("Low: %d\n", nums.stream().sorted().findFirst().get());
System.out.printf("High: %d\n",nums.stream().sorted().reduce((previous,current)->current).get());
Needs Java 8 if your on an older jdk.
 

Visual Studio

The Original Shiba Inu
Messages
2,775
Reaction score
1,485
I was approached by another student again yesterday that is taking a Java course and he asked how to determine the highest and lowest number in a set array. Since I have already taken a few Java courses and taught myself most of the language I decided to help him out and write him a snippet of code. So whenever a fellow student comes to me for help I will release it here on Se7ensins because I noticed some of the developers here are starting college and they will need to know some of this basic knowledge. I hope this helps someone out in the log run because I know small applications like this really helped me when learning how to code. Enjoy!

Java:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package lowest.and.highest.number;
import java.util.*;

/**
*
* @author Chris
*/
public class LowestAndHighestNumber {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args)
    {
        int num1;
        int num2;
        int num3;
        int num4;
        int num5;
   
        Scanner userInput = new Scanner(System.in);
        System.out.println("Please enter a set of numbers (Max - 5 Numbers):");
        num1 = userInput.nextInt();
        num2 = userInput.nextInt();
        num3 = userInput.nextInt();
        num4 = userInput.nextInt();
        num5 = userInput.nextInt();
   
        int numbers[] = {num1, num2, num3, num4, num5};
        int largestNumber = numbers[0];
        int smallestNumber = numbers[0];
   
        for(int i = 0; i < numbers.length; i++)
        {
            if(numbers[i] > largestNumber)
            {
                largestNumber = numbers[i];
            }
       
            if (numbers[i] < smallestNumber)
            {
                smallestNumber = numbers[i];
            }
        }

        System.out.println("The largest number in the set {" + num1 + ", " + num2 + ", " + num3 + ", " + num4 + ", " + num5 + "} is " + largestNumber);
        System.out.println("The smallest number in the set {" + num1 + ", " + num2 + ", " + num3 + ", " + num4 + ", " + num5 + "} is " + smallestNumber);
    }

}
And here is the output of the application:
I wish more languages were as short-typed as python :cry:
Code:
__author__ = 'John'

import os

numbers = []
print "Enter 5 numbers:"
for x in range(1, 6):
    numbers.append(int(raw_input("Number #" + str(x) + ": ").strip()))
print "Smallest: " + str(min(numbers)) + os.linesep + "Largest: " + str(max(numbers))
 

Chris7S

Nerd by definition, programmer by trade
Messages
1,522
Reaction score
490
I wish more languages were as short-typed as python :cry:
Code:
__author__ = 'John'

import os

numbers = []
print "Enter 5 numbers:"
for x in range(1, 6):
    numbers.append(int(raw_input("Number #" + str(x) + ": ").strip()))
print "Smallest: " + str(min(numbers)) + os.linesep + "Largest: " + str(max(numbers))
Python is such a beautiful, simplistic language.
 

YYes

Enthusiast
Messages
177
Reaction score
52
> people who call python syntax "beautiful" :banghead:

It's slow as hell but it's the tool for any job.
 

Visual Studio

The Original Shiba Inu
Messages
2,775
Reaction score
1,485
> people who call python syntax "beautiful" :banghead:

It's slow as hell but it's the tool for any job.
Speed is one of the selling points on python though... Compared to other scripting languages it's extremely fast but compared to compiled languages it's not very fast.
 

Chris7S

Nerd by definition, programmer by trade
Messages
1,522
Reaction score
490
> people who call python syntax "beautiful" :banghead:

It's slow as hell but it's the tool for any job.
Python has many advantages and is used for a lot of scripting that runs some small scale hardware which is always fun to tinker with.
 

YYes

Enthusiast
Messages
177
Reaction score
52
Python has many advantages and is used for a lot of scripting that runs some small scale hardware which is always fun to tinker with.
I worked for a company whose whole API and server was written in Python. I wouldn't call it small by any means. Python can entirely replace MatLab in capability, and can be used for almost any purpose with its huge libraries. Personally, I am just not a fan of dynamically typed, non-compiled languages.
 

Drgstr420

Enthusiast
Messages
517
Reaction score
63
Or use streams and do it in 3 lines.
Clean code != short code always. The way you did it is still clean, however is not beginner friendly like I was trying to be. I wouldn't expect a beginner to understand java 8 features such as streams and lambdas.
 

YYes

Enthusiast
Messages
177
Reaction score
52
Clean code != short code always. The way you did it is still clean, however is not beginner friendly like I was trying to be. I wouldn't expect a beginner to understand java 8 features such as streams and lambdas.
Clean code's not always short. Moreover, the question here is whether you want you use a library algorithm (optimized) or demonstrate an algo. of your own, like my last post. I.e. an O(num) function, with size of sizeof(int)*2. (correct(me(if(im(wrong))))) :cigar:
 

Chris7S

Nerd by definition, programmer by trade
Messages
1,522
Reaction score
490
I worked for a company whose whole API and server was written in Python. I wouldn't call it small by any means. Python can entirely replace MatLab in capability, and can be used for almost any purpose with its huge libraries. Personally, I am just not a fan of dynamically typed, non-compiled languages.
You misunderstood what I was saying. I was giving an example of Python scripts being used for but not exclusive to the Arduino motherboards. Yes I know it is extremely powerful and I have written an entire backend for a website using Python but I do agree with you. It is very simple yet powerful like Visual Basic but I am not a huge fan personally though there are situations where it is extremely useful.
 

YYes

Enthusiast
Messages
177
Reaction score
52
You misunderstood what I was saying. I was giving an example of Python scripts being used for but not exclusive to the Arduino motherboards. Yes I know it is extremely powerful and I have written an entire backend for a website using Python but I do agree with you. It is very simple yet powerful like Visual Basic but I am not a huge fan personally though there are situations where it is extremely useful.
ah yea I totally did. I thought arduino was basically just c code?
 

MatthewH

Member
Messages
1,612
Reaction score
628
ah yea I totally did. I thought arduino was basically just c code?
Arduino is C. Now I'm sure there's a way to run other languages, but originally it's just C.
Correct if I'm wrong C Chris7S but he is saying more that Python would be used to communicate with the Arduino. I can use C# and communicate with an Arduino, which I have done (uploading sketches and stuff, nothing major).
However, if you're running Python on the Arduino itself, please share with me more details on that because I would love to know.
 

Chris7S

Nerd by definition, programmer by trade
Messages
1,522
Reaction score
490
ah yea I totally did. I thought arduino was basically just c code?
Arduino is C. Now I'm sure there's a way to run other languages, but originally it's just C.
Correct if I'm wrong C Chris7S but he is saying more that Python would be used to communicate with the Arduino. I can use C# and communicate with an Arduino, which I have done (uploading sketches and stuff, nothing major).
However, if you're running Python on the Arduino itself, please share with me more details on that because I would love to know.
You are correct. C is what is used to communicate with many versions of the Arduino but I personally compiled my scripts and was able to communicate with the board. Of course this is used on a much smaller scale because it will tend to get a little buggy but you can run simple IO tasks. I was able to create a binary clock using Python which was the first time I attempted to use it. I also think there are some external libraries, software, etc. that allow you to perform more 'resource hungry' tasks seamlessly. I believe that the Arduino Yun comes with Python installed and you also have the option to use Ruby, PHP and maybe a few others. I don't mess with Arduino boards much anymore because if I have a hardware project I want to work on I will choose the Raspberry Pi any day.
 
Last edited:
Top Bottom