Java Snippets

Hamburger icon

The Commons class

This is a final class that contains static functions that can be called inside the other programs in the repo without having to create and object.

Methods:

Method twoDecimals()

The function Commons.twoDecimals() uses format method of the class String that allows to format the basic types, but converts them into a String object. Since this function depends on the localization, your decimals could appear with commas instead of dots, thats why we add Locale.US. We also have to import the class where Locale is:

import java.util.Locale;

...

public static String Commons.twoDecimals(double r) {
	String sr = String.format(Locale.US, "%.2f", r);
	return sr;
}

This function can be extended to include truncating to n decimals, for example, adding n as a parameter.

Method readDouble()

The function Commons.readDouble() is used to read a number entered by keyboard input, and to check that it is indeed a number. To avoid working with exceptions, the method hasNextDouble() of the class "Scanner" is used. If the result of the method is true, the string read by keyboard input is parsed to double:

String s = reader.nextLine();
Scanner sc = new Scanner(s);

if ( sc.hasNextDouble() ) {
	d = Double.parseDouble(s);
}

If the result were false, the program would keep asking to enter a number until a number is entered.

You can enter decimal numbers with this technique, but they must be written in scientific notation. For example, for 2.3 you will write 23e-1.

Here the whole code of the function:

public static double readDouble() {
	Scanner reader = new Scanner(System.in);
	boolean b = true;
	double  d = 0;

	do {
		String s = reader.nextLine();
		Scanner sc = new Scanner(s);

		if ( sc.hasNextDouble() ) {
			b = false;
			d = Double.parseDouble(s);
		}
		else {
			b = true;
			System.out.print("ERROR - You must introduce a number: ");
		}

	} while (b);

	return d;
}

Method readInt()

Same as readDouble(), but for int.

View Commons's repo