# Java Highest and Lowest Number from a Set Application

Discussion in 'Source Code & Tutorial Database' started by Chris7S, Oct 23, 2014 with 22 replies and 1,184 views.

1. ### Chris7SNerd by definition, programmer by trade

Messages:
1,508
Ratings:
471
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!

Code:
```/*
* 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: Apr 23, 2015

Replies:
2
Views:
1,597

Replies:
3
Views:
442

Replies:
11
Views:
2,397

Replies:
0
Views:
432

Replies:
5
Views:
2,038
3. ### Drgstr420Enthusiast

Messages:
507
Ratings:
60
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.

• Like x 4
4. ### DatBoiJay53Enthusiast

Messages:
638
Ratings:
103
Can you please explain how this code isnt 'clean' ?

• Like x 1
5. ### Drgstr420Enthusiast

Messages:
507
Ratings:
60
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();
}
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

• Like x 1
6. ### Chris7SNerd by definition, programmer by trade

Messages:
1,508
Ratings:
471
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.

7. ### Im4eversmartThe hacks are real

Messages:
2,098
Ratings:
1,669
Or use streams and do it in 3 lines.

• Like x 1
8. ### YYesEnthusiast

Messages:
177
Ratings:
49
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.
Code:
```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: May 4, 2015
9. ### Im4eversmartThe hacks are real

Messages:
2,098
Ratings:
1,669
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.

10. ### Visual StudioThe Original Shiba Inu

Messages:
2,766
Ratings:
1,343
I wish more languages were as short-typed as python
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))```

• Like x 1
11. ### Chris7SNerd by definition, programmer by trade

Messages:
1,508
Ratings:
471
Python is such a beautiful, simplistic language.

• Like x 1
12. ### YYesEnthusiast

Messages:
177
Ratings:
49
> people who call python syntax "beautiful"

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

13. ### Visual StudioThe Original Shiba Inu

Messages:
2,766
Ratings:
1,343
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.

• Like x 1
14. ### Chris7SNerd by definition, programmer by trade

Messages:
1,508
Ratings:
471
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.

15. ### YYesEnthusiast

Messages:
177
Ratings:
49
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.

16. ### Drgstr420Enthusiast

Messages:
507
Ratings:
60
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.

17. ### YYesEnthusiast

Messages:
177
Ratings:
49
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)))))

18. ### Chris7SNerd by definition, programmer by trade

Messages:
1,508
Ratings:
471
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.

19. ### YYesEnthusiast

Messages:
177
Ratings:
49
ah yea I totally did. I thought arduino was basically just c code?

20. ### MatthewHMember

Messages:
1,612
Ratings:
614
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 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.

21. ### Chris7SNerd by definition, programmer by trade

Messages:
1,508
Ratings:
471
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: May 15, 2015