Replace regex matched substring by another substring in Java

The goal of this post is to show how to match words and replace them in a string using java. We are looking for words of three characters that start with a lower case letter and are followed by two digits. It took me a while to remember about the word boundaries (those represented by \\b). Pay attention to that. By the way, this exercise I found on the book Competitive Programming. ...

September 8, 2016 · 1 min

How to eval a math expression entered as an input string in Java

One way to evaluate simple math expressions in Java just takes a couple lines of code. It uses Javascript’s engine to do that and it is quite useful. // to use eval import javax.script.ScriptEngineManager; import javax.script.ScriptEngine; // to use scanner import java.util.*; class Main { public static void main(String[] args) throws Exception { ScriptEngineManager mgr; mgr = new ScriptEngineManager(); ScriptEngine engine; engine = mgr.getEngineByName("JavaScript"); Scanner scan = new Scanner(System.in); String foo = scan.nextLine(); System.out.println(engine.eval(foo)); } } If you want to compile and run this example, you need to have Java JDK installed. The commands to compile and run a file called eval.java with the code above are: ...

September 8, 2016 · 1 min

Print double in Java with variable precision

There are some details I never cared about that I started to learn. One of them is just printing to the screen with variable precision. The solution is quite simple. import java.util.*; /** * Prints pi with n decimal places. * n is given by the user */ class Main { public static void main(String[] args) { double pi = Math.PI; Scanner scanner = new Scanner(System.in); int precision = scanner.nextInt(); scanner.close(); String format = "%." + precision + "f\n"; System.out.printf(format, pi); } } The difficulty is just thinking that you can define a string with the precision you want and then use it to print to the screen. ...

September 8, 2016 · 1 min