scrollIcon

Java Utility Methods

There's method to our madness!

These are some helpful methods we've developed over the course of our Java adventures. Think of them as gadgets in Batman's Utility Belt! Zowie! They sure can come in handy!

While there is never a guarantee, these methods have been tested 'in the wild' and we believe they are bullet-proof and robust!

I/O Utilities
Method
Filtered User Input in a Range

10/17/2022

public static long inputLongInRange(String p, long min, long max){
    Scanner input = new Scanner(System.in);
    long myLong = 10; //arb initializing value
    
    boolean acceptable = false; //assume bad input till its not
    
    do{
        System.out.print(p); //a meaningful prompt (nudge) for info
        myLong = input.nextLong();
        if(myLong >= min && myLong <= max) acceptable = true;
        else acceptable = false;
    }while(!acceptable);
        
    input.close(); //good practice
    return myLong;
}//end method inputLongInRange
                                    
Print a 'Curated' Title

10/18/2022

public static void printTitle(String t, String stage, int num, char ch, int lines){
    String bumper = "";
    String title = t + " Stage-" + stage;
    for(int i = 1; i <= num; i++) bumper += ch;
    System.out.println(bumper + " " + title + " " + bumper);
    for(int i = 1; i <= lines; i++) System.out.print("\n");
}//end method printTitle
                                    
Read String data from a text file into an ArrayList

12/07/2022

import java.io.*;
import java.util.StringTokenizer;
import java.util.ArrayList;
...
public static ArrayList<String> readStringData(String fileName){
    //reads string (words) entries from an Excel text file
    ArrayList <String> myData = new ArrayList <String>();
    String entry;
    StringTokenizer tokenizer;
    try{
        FileReader inFile = new FileReader(fileName);
        BufferedReader inStream = new BufferedReader(inFile);
        while((entry = inStream.readLine()) != null){
            //entries in Excel when converted to text are separated by tabs
            tokenizer = new StringTokenizer(entry, "\t"); //'\t' is escape sequence for 'tab'
            while(tokenizer.hasMoreTokens()){
                entry = tokenizer.nextToken();
                entry = entry.trim();
                myData.add(entry);
            }
        }
        inStream.close();
    }
    catch(Exception e){
        System.out.println("Exception e: " + e);
        System.out.println("There's been a problem. Program terminated.");
        System.exit(0);
    }
    return myData;
}//end readStringData
                                        
                                    
Math Utilities
Method
Extracting digits from an integer (2 ways)

10/31/2023

                                   
import java.util.Scanner;

public class ExtractingDigitsDriver{
    public static void main(String[] args){
        Scanner kb = new Scanner(System.in);
        int n = 7;  //dummy start value
        boolean showProcess = false;
        
        while(n > 0){
            System.out.print("Enter a positive integer (0 to end): ");
            n = kb.nextInt();
            if(n == 0) break;
            
            int myDigits1[] = extractDigitsWithMath(n, showProcess);
            int myDigits2[] = extractDigitsViaStringManip(n);
            System.out.println("Digits of " + n + ":");
            printArr(myDigits1);    //will be listed from right to left
            System.out.println();
            printArr(myDigits2);    //will be listed from left to right
        }//end loop
        
        System.out.println("\nThanks for using our program!");
    }//end main
    
    public static int[] extractDigitsWithMath(int n, boolean shouldShowProcess){
        String nStr = Integer.toString(n);
        int temp[] = new int[nStr.length()];
        int x = n;
        int ndx = 0;
        while(x > 0){
            int r = x % 10;
            if(shouldShowProcess){
                System.out.println(x + ", " + r);
            }
            temp[ndx] = r;
            x /= 10;
            ndx++;
        }
        return temp;
    }//end extractDigitsWithMath
    
    public static int[] extractDigitsViaStringManip(int n){
        //dwr! leading zeros not captured!
        
        //works:
        //String nStr = Integer.toString(n);
        //char myChars[] = nStr.toCharArray();
    
        //also works:
        char myChars[] = ("" + n).toCharArray();
        int temp[] = new int[myChars.length];
        for(int ndx = 0; ndx < myChars.length; ndx++){
            char aChar = myChars[ndx];
            //casting
            temp[ndx] = (int) aChar - 48; //ascii code for '0' is 48; '1' is 49, etc
        }
        return temp;
    }//end extractDigitsViaStringManip
    
    public static void printArr(int[] arr){
        for(int v : arr) System.out.println(v);
    }//end printArr
}//end class
                                    
Are two doubles equal?

09/05/2023

//https://stackoverflow.com/questions/8081827/how-to-compare-two-double-values-in-java                                        
public static boolean areTheseDoublesEqual(double x, double y){
    //Double.MIN_NORMAL is about 2.225E-308 
    return Math.abs(x - y) < Double.MIN_NORMAL;
}//end areTheseDoublesEqual
                                    
Rounding to Nearest 'n'th Decimal Place

10/17/2022

public static double roundToNearest(double x, int n){
    double roundedValue = x;
    double powTen = Math.pow(10, n);
    roundedValue = Math.round(roundedValue*powTen);
    roundedValue /= powTen;
    return roundedValue;
}//end roundToNearest
                                    
Is a number prime?

12/06/2022

public static boolean isPrime(long checkNumber){
    if(checkNumber == 1) return false;
    if(checkNumber == 2) return true;
    else if(checkNumber % 2 == 0) return false;	//even >2 not prime
    double root = Math.sqrt(checkNumber);
    double uBound = Math.ceil(root);
    for (long i = 3; i <= uBound; i+=2){
        if (checkNumber % i == 0) return false;
    }
    return true;
}//end isPrime
                                    
Get a 'repeatable'? random number in [min, max]

12/06/2022

public static int getRandom(Random rng, int min, int max){
    max = Math.max(min, max);
    min = Math.min(min, max);
    int range = max - min;
    int x = min + rng.nextInt(range + 1);
    return x;
}//end getRandom

public static double getRandom(Random rng, double min, double max){
    max = Math.max(min, max);
    min = Math.min(min, max);
    double range = max - min;
    double adjustedRange = range + Math.ulp(range);
    double x = min + adjustedRange*rng.nextDouble();
    return x;
}//end getRandom
                                    

Note that the rng parameter (random number generator) would be created with a call like: Random rng = new Random(seed); where seed is an integer. A sequence of random numbers initiated with a 'seeded' Random number generator is repeatable.

However, if the rng is created without a parameter (seed), (Random rng = new Random(seed);) then the resulting numbers from the rng are 'clock-seeded' and are not repeatable!

Get a random number in [min, max] using the Math class

12/06/2022

public static int getRandom(int min, int max){
    max = Math.max(min, max);
    min = Math.min(min, max);
    int range = max - min;
    int x = min + (int) (range + 1) * Math.random();
    return x;
}//end getRandom

public static double getRandom(double min, double max){
    max = Math.max(min, max);
    min = Math.min(min, max);
    double range = max - min;
    double adjustedRange = range + Math.ulp(range);
    double x = min + adjustedRange*Math.random();
    return x;
}//end getRandom
                                    

Note: Math.random() gives a value in [0, 1).

Get the median from an ArrayList<Integer>

02/25/2025

public static double findMedian(ArrayList<Integer> al){
    Collections.sort(al);
    System.out.println(al);
    int theSize = al.size();
    double median;
    if(theSize % 2 == 1){
        median = al.get(theSize/2);
    }else{
        int ndx1 = theSize/2 - 1;
        int ndx2 = ndx1 + 1;
        median = (al.get(ndx1) + al.get(ndx2))/2.0;
    }
    return median;
}//end findMedian
                                    

Note: It can be a decimal value not in the AL!

String Manipulation Utilities

There are additional String manipulation methods on our String Resources page as well

Method
Obtain Memory Address

09/01/2023

public static String obtainAddress(Object obj){
	int x = System.identityHashCode(obj);
	String x2 = Integer.toHexString(x);
	String info = "@" + x2;
	return info;
}//end obtainAddress

//if your class inherits directly from Object class
//you can use this easier method:
public static String obtainAddressViaObjectClass(){
	String memAddress = super.toString(); //assumes parent is 'Object' class
	return memAddress;
}//end obtainAddress
                                    
Remove Multiple Spaces

10/17/2022

public static String removeMultipleSpaces(String str){
    int len0 = str.length();
    String temp = str.trim();
    String doubleSpace = "  ";
    String singleSpace = " ";
    int count = 0; //accumulator
    while(temp.contains(doubleSpace)){
        temp = temp.replace(doubleSpace, singleSpace);
        count++;
    }//end loop
    //System.out.println("\n\tThere were: " + count + " loop runs");
    int lenf = temp.length();
    int diff = len0 - lenf;
    //System.out.println("\tThere were " + diff + " removed spaces");
    
    return temp;
}//end removeMultipleSpaces

/*
Additional code is there that counts and
echos the number of replacements and
the change in length of str. It's commented
out but could easily be reinserted.
*/
                                    
Quick-Access Templates
Method
Main Method

10/17/2022

/*
Coder:
Date:
File:
Info:
*/
public class MyTemplateDriver{
    public static void main(String args[]){
        String stageStr = "0";
        System.out.println("=== My Template Driver: Stage " + stageStr + " ===");

        System.out.println("Thanks for using our program!");
    }//end main method
}//end class
    
                                    
Class Shell

10/17/2022


//Perhaps (Clown Nonsense) Is Constructive (Only Toward)
//Getting Settler's Underwear
public class DoDah{
    //ivars

    //constructor(s)

    //overridden methods

    //getters

    //setters

    //utilities
}//end class