Transformation of a number to different number using recursion - java

I am trying to make an algorithm for the following task:
I have two integers a ≤ b
The algorithm has to transform a into b by adding 1 and multiply by 2 operations. For example, if a = 5 and b = 23 the program should output something like 23 = ((5 * 2 + 1) * 2 + 1)
I have to use recursion
I've already Googled many times but all I could find is ideas on how to transform a matrix, how to do geometric transformations, how to transform string into another string and similar stuff.
Does anybody have any ideas?

This is the way to find the transformation with the minimum number of operations:
(EDIT: Added parenthesis)
public static void main (String [] args)
{
int a = 5, b = 23;
System.out.println (transform (a, b) + " = " + b);
}
public static String transform (int a, int b)
{
if (a == b) return "" + a;
if (b % 2 == 0 && 2 * a <= b)
{
b = b / 2;
return transform (a, b) + " * 2";
}
else
{
b = b - 1;
return "(" + transform (a, b) + " + 1)";
}
}

This actually prints it, but it may not be exactly what you are looking for I'm not sure.
private static String doDo(int a, int b, StringBuilder sb) {
if (a == b) {
String ret = sb.toString();
int charCount = ret.replaceAll("[^)]", "").length();
for (int i = 0; i < charCount; i++)
ret = "(" + ret;
return ret;
}
if (a < (b/2f)) {
sb.append(")*2+1");
return doDo(a*2 + 1, b, sb);
} else {
sb.append("+1");
return doDo(a+1, b, sb);
}
}
System.out.println(doDo(5, 23, new StringBuilder().append("5")));
This is printed -> ((5)*2+1)*2+1

Following method should work for you I think:
int transform(int a, int b) {
if (a>= b)
return a;
else if (a*2 <= b)
return transform(2*a, b);
else
return transform(a + 1, b);
}

here's some pseudo code that you can use
transform(a, b)
start
if a >= b
return
else
print formatted progress
transform(a * 2 + 1, b)
end

If you don't want to over shoot then use this (modified version of #anubhava's solution).
int transform(int a, int b) {
if (a >= b){
return a;
} else {
int c = a*2 + 1;
if (c>b){
return a;
} else {
return transform(c, b);
}
}
}

Here's a version that uses recursion to determine the optimal strategy for doing the transform in the minimal number of operations. I assume that each time you double, that counts as one operation; each time you add 1, that counts as one operation, and the goal is to minimise the total number of operations.
And testing it on the 5->23 example yields:
((((5)*2)+1)*2)+1=23
You could be terser with the syntax, but hopefully a little verbosity helps to show the intent of the code.
Hat tip to josh.trow as I used his idea on how to do the string formatting.
import java.util.ArrayList;
import java.util.List;
public class DoubleAndAddAlgorithm {
public enum Op {
DOUBLE, ADD_ONE
}
private static List<Op> getOptimalTransform(int a, int b) throws IllegalArgumentException {
// Returns the list of operations that comprises the optimal way to get from a to b
// If a is already bigger than b, we have a problem
if (a > b) {
throw new IllegalArgumentException("a cannot be greater than b");
}
List<Op> result = new ArrayList<Op>();
// If we can get there in one operation, do so
if (2*a == b) {
result.add(Op.DOUBLE);
} else if (a+1 == b) {
result.add(Op.ADD_ONE);
}
// If doubling would cause us to overshoot, all we can do is add 1
// and take it from there...
else if (2*a > b) {
result.add(Op.ADD_ONE);
result.addAll(getOptimalTransform(a+1, b));
}
// Otherwise, let's try doubling, and let's try adding one, and use
// recursion to see which gets us to the target quicker
else {
List<Op> trialResultDouble = getOptimalTransform(2*a, b);
List<Op> trialResultAddOne = getOptimalTransform(a+1, b);
// Let's say (arbitrarily), that if neither operation results in us
// getting to the target any quicker than the other, we choose to add 1
if (trialResultDouble.size() < trialResultAddOne.size()) {
result.add(Op.DOUBLE);
result.addAll(trialResultDouble);
} else {
result.add(Op.ADD_ONE);
result.addAll(trialResultAddOne);
}
}
return result;
}
public static String getFormattedResult(int a, int b) {
try {
List<Op> ops = getOptimalTransform(a, b);
StringBuilder sb = new StringBuilder();
sb.append(Integer.toString(a));
for (Op op: ops) {
if (op == Op.DOUBLE) {
sb.insert(0, "(");
sb.append(")*2");
} else if (op == Op.ADD_ONE) {
sb.insert(0, "(");
sb.append(")+1");
}
}
sb.append("=");
sb.append(Integer.toString(b));
return sb.toString();
} catch (IllegalArgumentException e) {
return "Illegal arguments supplied";
}
}
public static void main(String[] args) {
System.out.println( getFormattedResult(5, 23) );
}
}

Search for an algorithm called double&add, it's the dual of the square&multiply one...i'm sorry but i don't know the details.

Related

Making a recursive method to print a text in java

I have to make a program which works like this. first it gets a number from input and then it gets (number) * strings.
for example:
2
a b
or
3
x1 x2 x3
then in the output it prints something like this:
Math.max(a, b)
or
Math.max(x1, Math.max(x2, x3))
I want to make Math.max method syntax with this code. I hope you understood!
Another Sample Input & output:
Input =
4
a b c d
Output =
Math.max(a, Math.max(b, Math.max(c, d)))
can someone help me?
The code I've wrote for it, can you suggest me some changes to make it better?
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n = input.nextInt();
String[] r = new String[n];
for (int i = 0; i < n; i++) {
r[i] = input.next();
}
printmax(r);
}
public static int i = 0 , j = 0;
public static boolean last = false;
public static void printmax(String [] r){
if (last == true) {
System.out.print(r[r.length - 1]);
while (j < r.length - 1){ System.out.print(")");
j++;
}
}
if (r.length == 2) System.out.print("Math.max(" +r[0] + ", " + r[1] + ")");
if (r.length > 2) {
while (i < r.length -1) {
if (i == r.length -2) last = true;
System.out.print("Math.max(" + r[i] + ", ");
i++;
printmax(r);
}
}
}
}
You can use the following code to achieve the above, here m calling maxElement() function recursively to achieve somthing like this Math.max(a, Math.max(b, Math.max(c, d)))
public static void main(String args[]){
int length = 2; //here read the input from scanner
String[] array = {"a", "b"}; //here read this input from scanner
String max = maxElement(array,0,length);
System.out.println(max);
}
public static String maxElement(String[] start, int index, int length) {
if (index<length-1) {
return "Math.max(" + start[index] + ", " + maxElement(start, index+1, length)+ ")";
} else {
return start[length-1];
}
}
Output:
Math.max(a, b)
You need to do something like this.
First you define a function maxElement which takes your variable array as a parameter.
public static maxElement(String[] variables) {
return maxElementBis(variables,0);
}
Then you call a second function : maxElementBis which takes an additional argument which represents the index of the variable we are processing.
public static String maxElementBis(String[] variables, int index) {
if (variables.length < 2)
return "not enought variables";
if (variables.length - index == 2)
return "Math.max("+ variables[index]+","+variables[index + 1]+")";
return "Math.max("+ variables[index]+","+maxElementBis(variables,index + 1)+")";
}
If the array contains less than two variables you cannot do what you want.
If you only have two variables left, this is your stop condition and you can directly return Math.max(v1,v2).
Otherwise you recursively call your function maxElementBis.

Quick sort not sorting array [duplicate]

This question already has answers here:
Is Java "pass-by-reference" or "pass-by-value"?
(93 answers)
Closed 4 years ago.
I have the following code:
public class Main {
static void swap (Integer x, Integer y) {
Integer t = x;
x = y;
y = t;
}
public static void main(String[] args) {
Integer a = 1;
Integer b = 2;
swap(a, b);
System.out.println("a=" + a + " b=" + b);
}
}
I expect it to print a=2 b=1, but it prints the opposite. So obviously the swap method doesn't swap a and b values. Why?
This doesn't have anything to do with immutability of integers; it has to do with the fact that Java is Pass-by-Value, Dammit! (Not annoyed, just the title of the article :p )
To sum up: You can't really make a swap method in Java. You just have to do the swap yourself, wherever you need it; which is just three lines of code anyways, so shouldn't be that much of a problem :)
Thing tmp = a;
a = b;
b = tmp;
Everything in Java is passed by value and the values of variables are always primitives or references to object.
If you want to implement a swap method for Integer objects, you have to wrap the values into an array (or ArrayList) and swap inside the array. Here's an adaptation of your code:
public class Main {
static void swap (Integer[] values) {
if ((values == null) || (values.length != 2)) {
throw new IllegalArgumentException("Requires an array with exact two values");
}
Integer t = values[0];
values[0] = values[1];
values[1] = t;
}
public static void main(String[] args) {
Integer a = 1;
Integer b = 2;
Integer[] integers= new Integer[]{a,b};
swap(integers);
System.out.println("a=" + integers[0] + " b=" + integers[1]);
}
}
(Just added this answer because Svish mentioned, that "You can't really make a swap method in Java" fg)
As Svish and others pointed out it it's call by value, not by reference in Java. Since you have no pointers in Java you need some kind of holder object to really swap values this way. For example:
static void swap(AtomicReference<Integer> a, AtomicReference<Integer> b) {
Integer c = a.get();
a.set(b.get());
b.set(c);
}
public static void main(String[] args) {
AtomicReference<Integer> a = new AtomicReference<Integer>(1);
AtomicReference<Integer> b = new AtomicReference<Integer>(2);
System.out.println("a = " + a);
System.out.println("b = " + b);
swap(a, b);
System.out.println("a = " + a);
System.out.println("b = " + b);
}
You would need to pass the parameters by reference, which it's not possible in java. Also Integers are inmutables, so you cannot exchange the values as you don't have a setValue method.
Integer are immutable - you can't change their values. The swapping that occurs inside the swap function is to the references, not the values.
You would need to return both references in an array to achieve what you want
static Integer[] swap(Integer a, Integer b) {
return new Integer[]{b, a};
}
public static void main(String[] args) {
Integer a = 1;
Integer b = 2;
Integer[] intArray = swap(a, b);
a = intArray[0];
b = intArray[1];
System.out.println("a=" + a + " b=" + b);
}
If Integer had a setValue method, you could do something like this.
static void swap(Integer a, Integer b) {
int temp = a.intValue();
a.setValue(b.intValue());
b.setValue(temp);
}
But it doesn't - so to achieve what you want, return an array.
Using the XOR operator is a very bad idea:
First, it is far less readable. Second, there were times when this was faster but nowadays the opposite is the case. See
Wikipedia
for reference.
As all the guys mentioned its a Pass-By-Value thing.
Just liked to add: you can use this method of swapping GLOBAL integers.
private void swap (){
a ^= b;
b ^= a;
a ^= b;
}
It eliminates the use of another variable, and its just cooler :)
Java code:
class swap {
int n1;
int n2;
int n3;
void valueSwap() {
n3 = n1;
n1 = n2;
n2 = n3;
}
public static void main(String[] arguments) {
Swap trial = new Swap();
trial.n1 = 2;
trial.n2 = 3;
System.out.println("trial.n1 = " + trial.n1);
System.out.println("trial.n2 = " + trial.n2);
trial.valueSwap();
System.out.println("trial.n1 = " + trial.n1);
System.out.println("trial.n2 = " + trial.n2);
}
}
Output:
trial.n1 = 2
trial.n2 = 3
trial.n1 = 3
trial.n2 = 2
Using Scanner:
import java.util.*;
public class Swap {
public static void main(String[] args){
int i,temp,Num1,Num2;
Scanner sc=new Scanner(System.in);
System.out.println("Enter Number1 and Number2");
Num1=sc.nextInt();
Num2=sc.nextInt();
System.out.println("Before Swapping Num1="+Num1+" Num2="+Num2);
temp=Num1;
Num1=Num2;
Num2=temp;
System.out.println("After Swapping Num1="+Num1+" Num2="+Num2);
}
}

Numbers in descending order in Java using if/else only

How can I create a java program using only if / else to order 3 numbers in descending order. I can not use for processes or array. Numbers are entered by the user.
Here's what i have so far. What should i do, is the user enters two integers that are the same? The code can only display one output.
import java.util.Scanner;
public class DescendingOrder
{
public static void main(String [] args)
{
//variable dec.
int a;
int b;
int c;
Scanner kbd = new Scanner(System.in);
//user prompt
System.out.println("Please enter three integers");
a=kbd.nextInt();
b=kbd.nextInt();
c=kbd.nextInt();
//program output
if (a>=b && b>=c && a>=c)
{
System.out.println("a b c");
}
if (a>=c && c>=b && a>=b )
{
System.out.println("a c b");
}
if (b>=a && a>=c && b>=c)
{
System.out.println("b a c");
}
if (b>=c && c>=a && b>=c)
{
System.out.println("b c a");
}
if(c>=a && a>=b && c>=b)
{
System.out.println("c a b");
}
if (c>= b && b>=a && c>=a)
{
System.out.println("c b a");
}
}
}
A simpler way you can do it is
if (a < b)
{
int temp = a;
a = b;
b = temp;
}
if (b < c)
{
int temp = b;
b = c;
c = temp;
}
if (a < b)
{
int temp = a;
a = b;
b = temp;
}
System.out.println(a + " " + b + " " + c);
If two numbers are the same it doesn't really matter, as 90 45 45 is the same as 90 45 45. (In the case of your code as written, however, you are correct in noticing that it does matter. You could fix this by changing all your if statements except the first one into else-if)
This question seems to be a thought exercise so consider this answer an alternative to the other correct answers for your consideration. Here my enterprise-y solution.
Step 0, refactor your code to make it testable and stub out the method that will do the actual work:
import static java.lang.System.in;
import static java.lang.System.out;
import java.util.Scanner;
public class DescendingOrder {
public static final void main(final String... args) { // unavoidable use of an array, please don't dock points
try (final Scanner kbd = new Scanner(in)) { // always close your Closeables
final int a = kbd.nextInt();
final int b = kbd.nextInt();
final int c = kbd.nextInt();
final DescendingOrder calculator = new DescendingOrder();
out.println(calculator.order(a, b, c));
}
}
public String order(final int a, final int b, final int c) {
return null;
}
}
Step 1, write a unit test:
import static java.lang.Integer.MAX_VALUE;
import static java.lang.Integer.MIN_VALUE;
import static org.junit.Assert.assertEquals;
import org.junit.Before;
import org.junit.Test;
public class DescendingOrderTest {
private DescendingOrder orderer;
#Before
public void setUp() throws Exception {
orderer = new DescendingOrder();
}
#Test
public final void testOrderABC() {
final String result = orderer.order(MAX_VALUE, 0, MIN_VALUE); // don't forget the edge cases
assertEquals(MAX_VALUE + " " + 0 + " " + MIN_VALUE, result);
}
#Test
public final void testOrderACB() {
final String result = orderer.order(13, 5, 8);
assertEquals("13 8 5", result);
}
#Test
public final void testOrderBAC() {
final String result = orderer.order(4, 8, 2);
assertEquals("8 4 2", result);
}
#Test
public final void testOrderBCA() {
final String result = orderer.order(-8, -2, -4); // don't forget negative numbers
assertEquals("-2 -4 -8", result);
}
#Test
public final void testOrderCAB() {
final String result = orderer.order(1, -5, 5);
assertEquals("5 1 -5", result);
}
#Test
public final void testOrderCBA() {
final String result = orderer.order(MAX_VALUE, 0, MIN_VALUE);
assertEquals(MAX_VALUE + " " + 0 + " " + MIN_VALUE, result);
}
#Test
public final void testAllSame() {
final String result = orderer.order(53, 53, 53);
assertEquals("53 53 53", result);
}
}
Step 2, iteratively implement order until your tests pass:
public String order(final int a, final int b, final int c) {
if (a > b && a > c) {
return a + " " + order(b, c);
} else if (b > a && b > c) {
return b + " " + order(a, c);
}
return c + " " + order(a, b);
}
protected String order(final int x, final int y) {
if (x > y) {
return x + " " + y;
}
return y + " " + x;
}
It might not be the most computationally efficient, but I kept the method sizes small so it is clear what the code is meant to accomplish. I also do not need to scan through six scenarios to see that it is correct. If I assume that order( int, int ) is correct, then I only need to work through three scenarios to see that order( int, int, int ) is correct.
Obviously, this is overkill. But those constraints would never really exist.
I think your code was fine you were just printing wrong. You have to understand that a,b,c are variable of type int. when you use the + operator with two ints it performs an addition. If you use the + operator with an int and with a string it produces a concatenation. The int 'calls' to string turning the int into a string which produces String + String = concatenation.
Anyways, I think this is what you wanted. Let me know if this is what you wanted.
import java.util.Scanner;
public class Stackoverflow
{
public static void main(String [] args)
{
//variable dec.
int a;
int b;
int c;
Scanner kbd = new Scanner(System.in);
//user prompt
System.out.println("Please enter three integers");
a=kbd.nextInt();
b=kbd.nextInt();
c=kbd.nextInt();
//program output
if (a>=b && b>=c && a>=c)
{
System.out.println(a+" "+b+" "+c);
}
if (a>=c && c>=b && a>=b )
{
System.out.println(a+" "+c+" "+b);
}
if (b>=a && a>=c && b>=c)
{
System.out.println(b+" "+a+" "+c);
}
if (b>=c && c>=a && b>=c)
{
System.out.println(b+" "+c+" "+a);
}
if(c>=a && a>=b && c>=b)
{
System.out.println(c+" "+a+" "+b);
}
if (c>= b && b>=a && c>=a)
{
System.out.println(c+" "+b+" "+a);
}
}
}

Uva's 3n+1 problem

I'm solving Uva's 3n+1 problem and I don't get why the judge is rejecting my answer. The time limit hasn't been exceeded and the all test cases I've tried have run correctly so far.
import java.io.*;
public class NewClass{
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException {
int maxCounter= 0;
int input;
int lowerBound;
int upperBound;
int counter;
int numberOfCycles;
int maxCycles= 0;
int lowerInt;
BufferedReader consoleInput = new BufferedReader(new InputStreamReader(System.in));
String line = consoleInput.readLine();
String [] splitted = line.split(" ");
lowerBound = Integer.parseInt(splitted[0]);
upperBound = Integer.parseInt(splitted[1]);
int [] recentlyused = new int[1000001];
if (lowerBound > upperBound )
{
int h = upperBound;
upperBound = lowerBound;
lowerBound = h;
}
lowerInt = lowerBound;
while (lowerBound <= upperBound)
{
counter = lowerBound;
numberOfCycles = 0;
if (recentlyused[counter] == 0)
{
while ( counter != 1 )
{
if (recentlyused[counter] != 0)
{
numberOfCycles = recentlyused[counter] + numberOfCycles;
counter = 1;
}
else
{
if (counter % 2 == 0)
{
counter = counter /2;
}
else
{
counter = 3*counter + 1;
}
numberOfCycles++;
}
}
}
else
{
numberOfCycles = recentlyused[counter] + numberOfCycles;
counter = 1;
}
recentlyused[lowerBound] = numberOfCycles;
if (numberOfCycles > maxCycles)
{
maxCycles = numberOfCycles;
}
lowerBound++;
}
System.out.println(lowerInt +" "+ upperBound+ " "+ (maxCycles+1));
}
}
Are you making sure to accept the entire input? It looks like your program terminates after reading only one line, and then processing one line. You need to be able to accept the entire sample input at once.
I faced the same problem. The following changes worked for me:
Changed the class name to Main.
Removed the public modifier from the class name.
The following code gave a compilation error:
public class Optimal_Parking_11364 {
public static void main(String[] args) {
...
}
}
Whereas after the changes, the following code was accepted:
class Main {
public static void main(String[] args) {
...
}
}
This was a very very simple program. Hopefully, the same trick will also work for more complex programs.
If I understand correctly you are using a memoizing approach. You create a table where you store full results for all the elements you have already calculated so that you do not need to re-calculate results that you already know (calculated before).
The approach itself is not wrong, but there are a couple of things you must take into account. First, the input consists of a list of pairs, you are only processing the first pair. Then, you must take care of your memoizing table limits. You are assuming that all numbers you will hit fall in the range [1...1000001), but that is not true. For the input number 999999 (first odd number below the upper limit) the first operation will turn it into 3*n+1, which is way beyond the upper limit of the memoization table.
Some other things you may want to consider are halving the memoization table and only memorize odd numbers, since you can implement the divide by two operation almost free with bit operations (and checking for even-ness is also just one bit operation).
Did you make sure that the output was in the same order specified in the input. I see where you are swapping the input if the first input was higher than the second, but you also need to make sure that you don't alter the order it appears in the input when you print the results out.
ex.
Input
10 1
Output
10 1 20
If possible Please use this Java specification : to read input lines
http://online-judge.uva.es/problemset/data/p100.java.html
I think the most important thing in UVA judge is 1) Get the output Exactly same , No Extra Lines at the end or anywhere . 2) I am assuming , Never throw exception just return or break with No output for Outside boundary parameters.
3)Output is case sensitive 4)Output Parameters should Maintain Space as shown in problem
One possible solution based on above patterns is here
https://gist.github.com/4676999
/*
Problem URL: http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=36
Home>Online Judge > submission Specifications
Sample code to read input is from : http://online-judge.uva.es/problemset/data/p100.java.html
Runtime : 1.068
*/
import java.io.*;
import java.util.*;
class Main
{
static String ReadLn (int maxLg) // utility function to read from stdin
{
byte lin[] = new byte [maxLg];
int lg = 0, car = -1;
String line = "";
try
{
while (lg < maxLg)
{
car = System.in.read();
if ((car < 0) || (car == '\n')) break;
lin [lg++] += car;
}
}
catch (IOException e)
{
return (null);
}
if ((car < 0) && (lg == 0)) return (null); // eof
return (new String (lin, 0, lg));
}
public static void main (String args[]) // entry point from OS
{
Main myWork = new Main(); // create a dinamic instance
myWork.Begin(); // the true entry point
}
void Begin()
{
String input;
StringTokenizer idata;
int a, b,max;
while ((input = Main.ReadLn (255)) != null)
{
idata = new StringTokenizer (input);
a = Integer.parseInt (idata.nextToken());
b = Integer.parseInt (idata.nextToken());
if (a<b){
max=work(a,b);
}else{
max=work(b,a);
}
System.out.println (a + " " + b + " " +max);
}
}
int work( int a , int b){
int max=0;
for ( int i=a;i<=b;i++){
int temp=process(i);
if (temp>max) max=temp;
}
return max;
}
int process (long n){
int count=1;
while(n!=1){
count++;
if (n%2==1){
n=n*3+1;
}else{
n=n>>1;
}
}
return count;
}
}
Please consider that the integers i and j must appear in the output in the same order in which they appeared in the input, so for:
10 1
You should print
10 1 20
package pandarium.java.preparing2topcoder;/*
* Main.java
* java program model for www.programming-challenges.com
*/
import java.io.*;
import java.util.*;
class Main implements Runnable{
static String ReadLn(int maxLg){ // utility function to read from stdin,
// Provided by Programming-challenges, edit for style only
byte lin[] = new byte [maxLg];
int lg = 0, car = -1;
String line = "";
try
{
while (lg < maxLg)
{
car = System.in.read();
if ((car < 0) || (car == '\n')) break;
lin [lg++] += car;
}
}
catch (IOException e)
{
return (null);
}
if ((car < 0) && (lg == 0)) return (null); // eof
return (new String (lin, 0, lg));
}
public static void main(String args[]) // entry point from OS
{
Main myWork = new Main(); // Construct the bootloader
myWork.run(); // execute
}
public void run() {
new myStuff().run();
}
}
class myStuff implements Runnable{
private String input;
private StringTokenizer idata;
private List<Integer> maxes;
public void run(){
String input;
StringTokenizer idata;
int a, b,max=Integer.MIN_VALUE;
while ((input = Main.ReadLn (255)) != null)
{
max=Integer.MIN_VALUE;
maxes=new ArrayList<Integer>();
idata = new StringTokenizer (input);
a = Integer.parseInt (idata.nextToken());
b = Integer.parseInt (idata.nextToken());
System.out.println(a + " " + b + " "+max);
}
}
private static int getCyclesCount(long counter){
int cyclesCount=0;
while (counter!=1)
{
if(counter%2==0)
counter=counter>>1;
else
counter=counter*3+1;
cyclesCount++;
}
cyclesCount++;
return cyclesCount;
}
// You can insert more classes here if you want.
}
This solution gets accepted within 0.5s. I had to remove the package modifier.
import java.util.*;
public class Main {
static Map<Integer, Integer> map = new HashMap<>();
private static int f(int N) {
if (N == 1) {
return 1;
}
if (map.containsKey(N)) {
return map.get(N);
}
if (N % 2 == 0) {
N >>= 1;
map.put(N, f(N));
return 1 + map.get(N);
} else {
N = 3*N + 1;
map.put(N, f(N) );
return 1 + map.get(N);
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
try {
while(scanner.hasNextLine()) {
int i = scanner.nextInt();
int j = scanner.nextInt();
int maxx = 0;
if (i <= j) {
for(int m = i; m <= j; m++) {
maxx = Math.max(Main.f(m), maxx);
}
} else {
for(int m = j; m <= i; m++) {
maxx = Math.max(Main.f(m), maxx);
}
}
System.out.println(i + " " + j + " " + maxx);
}
System.exit(0);
} catch (Exception e) {
}
}
}

Good way to encapsulate Integer.parseInt()

I have a project in which we often use Integer.parseInt() to convert a String to an int. When something goes wrong (for example, the String is not a number but the letter a, or whatever) this method will throw an exception. However, if I have to handle exceptions in my code everywhere, this starts to look very ugly very quickly. I would like to put this in a method, however, I have no clue how to return a clean value in order to show that the conversion went wrong.
In C++ I could have created a method that accepted a pointer to an int and let the method itself return true or false. However, as far as I know, this is not possible in Java. I could also create an object that contains a true/false variable and the converted value, but this does not seem ideal either. The same thing goes for a global value, and this might give me some trouble with multithreading.
So is there a clean way to do this?
You could return an Integer instead of an int, returning null on parse failure.
It's a shame Java doesn't provide a way of doing this without there being an exception thrown internally though - you can hide the exception (by catching it and returning null), but it could still be a performance issue if you're parsing hundreds of thousands of bits of user-provided data.
EDIT: Code for such a method:
public static Integer tryParse(String text) {
try {
return Integer.parseInt(text);
} catch (NumberFormatException e) {
return null;
}
}
Note that I'm not sure off the top of my head what this will do if text is null. You should consider that - if it represents a bug (i.e. your code may well pass an invalid value, but should never pass null) then throwing an exception is appropriate; if it doesn't represent a bug then you should probably just return null as you would for any other invalid value.
Originally this answer used the new Integer(String) constructor; it now uses Integer.parseInt and a boxing operation; in this way small values will end up being boxed to cached Integer objects, making it more efficient in those situations.
What behaviour do you expect when it's not a number?
If, for example, you often have a default value to use when the input is not a number, then a method such as this could be useful:
public static int parseWithDefault(String number, int defaultVal) {
try {
return Integer.parseInt(number);
} catch (NumberFormatException e) {
return defaultVal;
}
}
Similar methods can be written for different default behaviour when the input can't be parsed.
In some cases you should handle parsing errors as fail-fast situations, but in others cases, such as application configuration, I prefer to handle missing input with default values using Apache Commons Lang 3 NumberUtils.
int port = NumberUtils.toInt(properties.getProperty("port"), 8080);
To avoid handling exceptions use a regular expression to make sure you have all digits first:
//Checking for Regular expression that matches digits
if(value.matches("\\d+")) {
Integer.parseInt(value);
}
There is Ints.tryParse() in Guava. It doesn't throw exception on non-numeric string, however it does throw exception on null string.
After reading the answers to the question I think encapsulating or wrapping the parseInt method is not necessary, maybe even not a good idea.
You could return 'null' as Jon suggested, but that's more or less replacing a try/catch construct by a null-check. There's just a slight difference on the behaviour if you 'forget' error handling: if you don't catch the exception, there's no assignment and the left hand side variable keeps it old value. If you don't test for null, you'll probably get hit by the JVM (NPE).
yawn's suggestion looks more elegant to me, because I do not like returning null to signal some errors or exceptional states. Now you have to check referential equality with a predefined object, that indicates a problem. But, as others argue, if again you 'forget' to check and a String is unparsable, the program continous with the wrapped int inside your 'ERROR' or 'NULL' object.
Nikolay's solution is even more object orientated and will work with parseXXX methods from other wrapper classes aswell. But in the end, he just replaced the NumberFormatException by an OperationNotSupported exception - again you need a try/catch to handle unparsable inputs.
So, its my conclusion to not encapsulate the plain parseInt method. I'd only encapsulate if I could add some (application depended) error handling as well.
May be you can use something like this:
public class Test {
public interface Option<T> {
T get();
T getOrElse(T def);
boolean hasValue();
}
final static class Some<T> implements Option<T> {
private final T value;
public Some(T value) {
this.value = value;
}
#Override
public T get() {
return value;
}
#Override
public T getOrElse(T def) {
return value;
}
#Override
public boolean hasValue() {
return true;
}
}
final static class None<T> implements Option<T> {
#Override
public T get() {
throw new UnsupportedOperationException();
}
#Override
public T getOrElse(T def) {
return def;
}
#Override
public boolean hasValue() {
return false;
}
}
public static Option<Integer> parseInt(String s) {
Option<Integer> result = new None<Integer>();
try {
Integer value = Integer.parseInt(s);
result = new Some<Integer>(value);
} catch (NumberFormatException e) {
}
return result;
}
}
You could also replicate the C++ behaviour that you want very simply
public static boolean parseInt(String str, int[] byRef) {
if(byRef==null) return false;
try {
byRef[0] = Integer.parseInt(prop);
return true;
} catch (NumberFormatException ex) {
return false;
}
}
You would use the method like so:
int[] byRef = new int[1];
boolean result = parseInt("123",byRef);
After that the variable result it's true if everything went allright and byRef[0] contains the parsed value.
Personally, I would stick to catching the exception.
I know that this is quite an old question, but I was looking for a modern solution to solve that issue.
I came up with the following solution:
public static OptionalInt tryParseInt(String string) {
try {
return OptionalInt.of(Integer.parseInt(string));
} catch (NumberFormatException e) {
return OptionalInt.empty();
}
}
Usage:
#Test
public void testTryParseIntPositive() {
// given
int expected = 5;
String value = "" + expected;
// when
OptionalInt optionalInt = tryParseInt(value);
// then
Assert.assertTrue(optionalInt.isPresent());
Assert.assertEquals(expected, optionalInt.getAsInt());
}
#Test
public void testTryParseIntNegative() {
// given
int expected = 5;
String value = "x" + expected;
// when
OptionalInt optionalInt = tryParseInt(value);
// then
Assert.assertTrue(optionalInt.isEmpty());
}
My Java is a little rusty, but let me see if I can point you in the right direction:
public class Converter {
public static Integer parseInt(String str) {
Integer n = null;
try {
n = new Integer(Integer.tryParse(str));
} catch (NumberFormatException ex) {
// leave n null, the string is invalid
}
return n;
}
}
If your return value is null, you have a bad value. Otherwise, you have a valid Integer.
The answer given by Jon Skeet is fine, but I don't like giving back a null Integer object. I find this confusing to use. Since Java 8 there is a better option (in my opinion), using the OptionalInt:
public static OptionalInt tryParse(String value) {
try {
return OptionalInt.of(Integer.parseInt(value));
} catch (NumberFormatException e) {
return OptionalInt.empty();
}
}
This makes it explicit that you have to handle the case where no value is available. I would prefer if this kind of function would be added to the java library in the future, but I don't know if that will ever happen.
What about forking the parseInt method?
It's easy, just copy-paste the contents to a new utility that returns Integer or Optional<Integer> and replace throws with returns. It seems there are no exceptions in the underlying code, but better check.
By skipping the whole exception handling stuff, you can save some time on invalid inputs. And the method is there since JDK 1.0, so it is not likely you will have to do much to keep it up-to-date.
If you're using Java 8 or up, you can use a library I just released: https://github.com/robtimus/try-parse. It has support for int, long and boolean that doesn't rely on catching exceptions. Unlike Guava's Ints.tryParse it returns OptionalInt / OptionalLong / Optional, much like in https://stackoverflow.com/a/38451745/1180351 but more efficient.
Maybe someone is looking for a more generic approach, since Java 8 there is the Package java.util.function that allows to define Supplier Functions. You could have a function that takes a supplier and a default value as follows:
public static <T> T tryGetOrDefault(Supplier<T> supplier, T defaultValue) {
try {
return supplier.get();
} catch (Exception e) {
return defaultValue;
}
}
With this function, you can execute any parsing method or even other methods that could throw an Exception while ensuring that no Exception can ever be thrown:
Integer i = tryGetOrDefault(() -> Integer.parseInt(stringValue), 0);
Long l = tryGetOrDefault(() -> Long.parseLong(stringValue), 0l);
Double d = tryGetOrDefault(() -> Double.parseDouble(stringValue), 0d);
I would suggest you consider a method like
IntegerUtilities.isValidInteger(String s)
which you then implement as you see fit. If you want the result carried back - perhaps because you use Integer.parseInt() anyway - you can use the array trick.
IntegerUtilities.isValidInteger(String s, int[] result)
where you set result[0] to the integer value found in the process.
This is somewhat similar to Nikolay's solution:
private static class Box<T> {
T me;
public Box() {}
public T get() { return me; }
public void set(T fromParse) { me = fromParse; }
}
private interface Parser<T> {
public void setExclusion(String regex);
public boolean isExcluded(String s);
public T parse(String s);
}
public static <T> boolean parser(Box<T> ref, Parser<T> p, String toParse) {
if (!p.isExcluded(toParse)) {
ref.set(p.parse(toParse));
return true;
} else return false;
}
public static void main(String args[]) {
Box<Integer> a = new Box<Integer>();
Parser<Integer> intParser = new Parser<Integer>() {
String myExclusion;
public void setExclusion(String regex) {
myExclusion = regex;
}
public boolean isExcluded(String s) {
return s.matches(myExclusion);
}
public Integer parse(String s) {
return new Integer(s);
}
};
intParser.setExclusion("\\D+");
if (parser(a,intParser,"123")) System.out.println(a.get());
if (!parser(a,intParser,"abc")) System.out.println("didn't parse "+a.get());
}
The main method demos the code. Another way to implement the Parser interface would obviously be to just set "\D+" from construction, and have the methods do nothing.
They way I handle this problem is recursively. For example when reading data from the console:
Java.util.Scanner keyboard = new Java.util.Scanner(System.in);
public int GetMyInt(){
int ret;
System.out.print("Give me an Int: ");
try{
ret = Integer.parseInt(keyboard.NextLine());
}
catch(Exception e){
System.out.println("\nThere was an error try again.\n");
ret = GetMyInt();
}
return ret;
}
To avoid an exception, you can use Java's Format.parseObject method. The code below is basically a simplified version of Apache Common's IntegerValidator class.
public static boolean tryParse(String s, int[] result)
{
NumberFormat format = NumberFormat.getIntegerInstance();
ParsePosition position = new ParsePosition(0);
Object parsedValue = format.parseObject(s, position);
if (position.getErrorIndex() > -1)
{
return false;
}
if (position.getIndex() < s.length())
{
return false;
}
result[0] = ((Long) parsedValue).intValue();
return true;
}
You can either use AtomicInteger or the int[] array trick depending upon your preference.
Here is my test that uses it -
int[] i = new int[1];
Assert.assertTrue(IntUtils.tryParse("123", i));
Assert.assertEquals(123, i[0]);
I was also having the same problem. This is a method I wrote to ask the user for an input and not accept the input unless its an integer. Please note that I am a beginner so if the code is not working as expected, blame my inexperience !
private int numberValue(String value, boolean val) throws IOException {
//prints the value passed by the code implementer
System.out.println(value);
//returns 0 is val is passed as false
Object num = 0;
while (val) {
num = br.readLine();
try {
Integer numVal = Integer.parseInt((String) num);
if (numVal instanceof Integer) {
val = false;
num = numVal;
}
} catch (Exception e) {
System.out.println("Error. Please input a valid number :-");
}
}
return ((Integer) num).intValue();
}
This is an answer to question 8391979, "Does java have a int.tryparse that doesn't throw an exception for bad data? [duplicate]" which is closed and linked to this question.
Edit 2016 08 17: Added ltrimZeroes methods and called them in tryParse(). Without leading zeroes in numberString may give false results (see comments in code). There is now also public static String ltrimZeroes(String numberString) method which works for positive and negative "numbers"(END Edit)
Below you find a rudimentary Wrapper (boxing) class for int with an highly speed optimized tryParse() method (similar as in C#) which parses the string itself and is a little bit faster than Integer.parseInt(String s) from Java:
public class IntBoxSimple {
// IntBoxSimple - Rudimentary class to implement a C#-like tryParse() method for int
// A full blown IntBox class implementation can be found in my Github project
// Copyright (c) 2016, Peter Sulzer, Fürth
// Program is published under the GNU General Public License (GPL) Version 1 or newer
protected int _n; // this "boxes" the int value
// BEGIN The following statements are only executed at the
// first instantiation of an IntBox (i. e. only once) or
// already compiled into the code at compile time:
public static final int MAX_INT_LEN =
String.valueOf(Integer.MAX_VALUE).length();
public static final int MIN_INT_LEN =
String.valueOf(Integer.MIN_VALUE).length();
public static final int MAX_INT_LASTDEC =
Integer.parseInt(String.valueOf(Integer.MAX_VALUE).substring(1));
public static final int MAX_INT_FIRSTDIGIT =
Integer.parseInt(String.valueOf(Integer.MAX_VALUE).substring(0, 1));
public static final int MIN_INT_LASTDEC =
-Integer.parseInt(String.valueOf(Integer.MIN_VALUE).substring(2));
public static final int MIN_INT_FIRSTDIGIT =
Integer.parseInt(String.valueOf(Integer.MIN_VALUE).substring(1,2));
// END The following statements...
// ltrimZeroes() methods added 2016 08 16 (are required by tryParse() methods)
public static String ltrimZeroes(String s) {
if (s.charAt(0) == '-')
return ltrimZeroesNegative(s);
else
return ltrimZeroesPositive(s);
}
protected static String ltrimZeroesNegative(String s) {
int i=1;
for ( ; s.charAt(i) == '0'; i++);
return ("-"+s.substring(i));
}
protected static String ltrimZeroesPositive(String s) {
int i=0;
for ( ; s.charAt(i) == '0'; i++);
return (s.substring(i));
}
public static boolean tryParse(String s,IntBoxSimple intBox) {
if (intBox == null)
// intBoxSimple=new IntBoxSimple(); // This doesn't work, as
// intBoxSimple itself is passed by value and cannot changed
// for the caller. I. e. "out"-arguments of C# cannot be simulated in Java.
return false; // so we simply return false
s=s.trim(); // leading and trailing whitespace is allowed for String s
int len=s.length();
int rslt=0, d, dfirst=0, i, j;
char c=s.charAt(0);
if (c == '-') {
if (len > MIN_INT_LEN) { // corrected (added) 2016 08 17
s = ltrimZeroesNegative(s);
len = s.length();
}
if (len >= MIN_INT_LEN) {
c = s.charAt(1);
if (!Character.isDigit(c))
return false;
dfirst = c-'0';
if (len > MIN_INT_LEN || dfirst > MIN_INT_FIRSTDIGIT)
return false;
}
for (i = len - 1, j = 1; i >= 2; --i, j *= 10) {
c = s.charAt(i);
if (!Character.isDigit(c))
return false;
rslt -= (c-'0')*j;
}
if (len < MIN_INT_LEN) {
c = s.charAt(i);
if (!Character.isDigit(c))
return false;
rslt -= (c-'0')*j;
} else {
if (dfirst >= MIN_INT_FIRSTDIGIT && rslt < MIN_INT_LASTDEC)
return false;
rslt -= dfirst * j;
}
} else {
if (len > MAX_INT_LEN) { // corrected (added) 2016 08 16
s = ltrimZeroesPositive(s);
len=s.length();
}
if (len >= MAX_INT_LEN) {
c = s.charAt(0);
if (!Character.isDigit(c))
return false;
dfirst = c-'0';
if (len > MAX_INT_LEN || dfirst > MAX_INT_FIRSTDIGIT)
return false;
}
for (i = len - 1, j = 1; i >= 1; --i, j *= 10) {
c = s.charAt(i);
if (!Character.isDigit(c))
return false;
rslt += (c-'0')*j;
}
if (len < MAX_INT_LEN) {
c = s.charAt(i);
if (!Character.isDigit(c))
return false;
rslt += (c-'0')*j;
}
if (dfirst >= MAX_INT_FIRSTDIGIT && rslt > MAX_INT_LASTDEC)
return false;
rslt += dfirst*j;
}
intBox._n=rslt;
return true;
}
// Get the value stored in an IntBoxSimple:
public int get_n() {
return _n;
}
public int v() { // alternative shorter version, v for "value"
return _n;
}
// Make objects of IntBoxSimple (needed as constructors are not public):
public static IntBoxSimple makeIntBoxSimple() {
return new IntBoxSimple();
}
public static IntBoxSimple makeIntBoxSimple(int integerNumber) {
return new IntBoxSimple(integerNumber);
}
// constructors are not public(!=:
protected IntBoxSimple() {} {
_n=0; // default value an IntBoxSimple holds
}
protected IntBoxSimple(int integerNumber) {
_n=integerNumber;
}
}
Test/example program for class IntBoxSimple:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class IntBoxSimpleTest {
public static void main (String args[]) {
IntBoxSimple ibs = IntBoxSimple.makeIntBoxSimple();
String in = null;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
do {
System.out.printf(
"Enter an integer number in the range %d to %d:%n",
Integer.MIN_VALUE, Integer.MAX_VALUE);
try { in = br.readLine(); } catch (IOException ex) {}
} while(! IntBoxSimple.tryParse(in, ibs));
System.out.printf("The number you have entered was: %d%n", ibs.v());
}
}
Try with regular expression and default parameters argument
public static int parseIntWithDefault(String str, int defaultInt) {
return str.matches("-?\\d+") ? Integer.parseInt(str) : defaultInt;
}
int testId = parseIntWithDefault("1001", 0);
System.out.print(testId); // 1001
int testId = parseIntWithDefault("test1001", 0);
System.out.print(testId); // 1001
int testId = parseIntWithDefault("-1001", 0);
System.out.print(testId); // -1001
int testId = parseIntWithDefault("test", 0);
System.out.print(testId); // 0
if you're using apache.commons.lang3 then by using NumberUtils:
int testId = NumberUtils.toInt("test", 0);
System.out.print(testId); // 0
I would like to throw in another proposal that works if one specifically requests integers: Simply use long and use Long.MIN_VALUE for error cases. This is similar to the approach that is used for chars in Reader where Reader.read() returns an integer in the range of a char or -1 if the reader is empty.
For Float and Double, NaN can be used in a similar way.
public static long parseInteger(String s) {
try {
return Integer.parseInt(s);
} catch (NumberFormatException e) {
return Long.MIN_VALUE;
}
}
// ...
long l = parseInteger("ABC");
if (l == Long.MIN_VALUE) {
// ... error
} else {
int i = (int) l;
}
Considering existing answers, I've copy-pasted and enhanced source code of Integer.parseInt to do the job, and my solution
does not use potentially slow try-catch (unlike Lang 3 NumberUtils),
does not use regexps which can't catch too big numbers,
avoids boxing (unlike Guava's Ints.tryParse()),
does not require any allocations (unlike int[], Box, OptionalInt),
accepts any CharSequence or a part of it instead of a whole String,
can use any radix which Integer.parseInt can, i.e. [2,36],
does not depend on any libraries.
The only downside is that there's no difference between toIntOfDefault("-1", -1) and toIntOrDefault("oops", -1).
public static int toIntOrDefault(CharSequence s, int def) {
return toIntOrDefault0(s, 0, s.length(), 10, def);
}
public static int toIntOrDefault(CharSequence s, int def, int radix) {
radixCheck(radix);
return toIntOrDefault0(s, 0, s.length(), radix, def);
}
public static int toIntOrDefault(CharSequence s, int start, int endExclusive, int def) {
boundsCheck(start, endExclusive, s.length());
return toIntOrDefault0(s, start, endExclusive, 10, def);
}
public static int toIntOrDefault(CharSequence s, int start, int endExclusive, int radix, int def) {
radixCheck(radix);
boundsCheck(start, endExclusive, s.length());
return toIntOrDefault0(s, start, endExclusive, radix, def);
}
private static int toIntOrDefault0(CharSequence s, int start, int endExclusive, int radix, int def) {
if (start == endExclusive) return def; // empty
boolean negative = false;
int limit = -Integer.MAX_VALUE;
char firstChar = s.charAt(start);
if (firstChar < '0') { // Possible leading "+" or "-"
if (firstChar == '-') {
negative = true;
limit = Integer.MIN_VALUE;
} else if (firstChar != '+') {
return def;
}
start++;
// Cannot have lone "+" or "-"
if (start == endExclusive) return def;
}
int multmin = limit / radix;
int result = 0;
while (start < endExclusive) {
// Accumulating negatively avoids surprises near MAX_VALUE
int digit = Character.digit(s.charAt(start++), radix);
if (digit < 0 || result < multmin) return def;
result *= radix;
if (result < limit + digit) return def;
result -= digit;
}
return negative ? result : -result;
}
private static void radixCheck(int radix) {
if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX)
throw new NumberFormatException(
"radix=" + radix + " ∉ [" + Character.MIN_RADIX + "," + Character.MAX_RADIX + "]");
}
private static void boundsCheck(int start, int endExclusive, int len) {
if (start < 0 || start > len || start > endExclusive)
throw new IndexOutOfBoundsException("start=" + start + " ∉ [0, min(" + len + ", " + endExclusive + ")]");
if (endExclusive > len)
throw new IndexOutOfBoundsException("endExclusive=" + endExclusive + " > s.length=" + len);
}
I've been using a helper class that contains a static Queue of parsed values, and I find it to look quite clean. This would be the helper class could look like:
public static class Parsing {
// Could optimise with specific queues for primitive types
// and also using a circular queue, instead of LinkedList
private static final Queue<Number> QUEUE = new LinkedList<Number>();
public static boolean parseInt(String value) {
// Could implement custom integer parsing here, which does not throw
try {
QUEUE.offer(Integer.parseInt(value));
return true;
}
catch (Throwable ignored) {
return false;
}
}
public static int getInt() {
return QUEUE.remove().intValue(); // user's fault if this throws :)
}
}
And then in code, you use it like this:
public Vector3 parseVector(String content) {
if (Parsing.parseInt(content)) {
return new Vector3(Parsing.getInt());
}
else {
String[] parts = content.split(",");
if (Parsing.parseInt(parts[0]) && Parsing.parseInt(parts[1]) && Parsing.parseInt(parts[2])) {
// the queue ensures these are in the same order they are parsed
return new Vector3(Parsing.getInt(), Parsing.getInt(), Parsing.getInt());
}
else {
throw new RuntimeException("Invalid Vector3");
}
}
}
The only problem with this, is that if you use multiple calls like i did above, but maybe the last one fails, then you'd have to roll back or clear the queue
Edit: You could remove the above problem and include some thread safely, by making the class non-static and, maybe for slightly cleaner code, make the class implement AutoCloseable so that you could do something like this:
public Vector3 parseVector(String content) {
try (Parsing parser = Parsing.of()) {
if (parser.parseInt(content)) {
return new Vector3(parser.getInt());
}
else {
String[] parts = content.split(",");
if (parser.parseInt(parts[0]) && parser.parseInt(parts[1]) && parser.parseInt(parts[2])) {
// the queue ensures these are in the same order they are parsed
return new Vector3(parser.getInt(), parser.getInt(), parser.getInt());
}
else {
throw new RuntimeException("Invalid Vector3");
}
}
}
}
You can use a Null-Object like so:
public class Convert {
#SuppressWarnings({"UnnecessaryBoxing"})
public static final Integer NULL = new Integer(0);
public static Integer convert(String integer) {
try {
return Integer.valueOf(integer);
} catch (NumberFormatException e) {
return NULL;
}
}
public static void main(String[] args) {
Integer a = convert("123");
System.out.println("a.equals(123) = " + a.equals(123));
System.out.println("a == NULL " + (a == NULL));
Integer b = convert("onetwothree");
System.out.println("b.equals(123) = " + b.equals(123));
System.out.println("b == NULL " + (b == NULL));
Integer c = convert("0");
System.out.println("equals(0) = " + c.equals(0));
System.out.println("c == NULL " + (c == NULL));
}
}
The result of main in this example is:
a.equals(123) = true
a == NULL false
b.equals(123) = false
b == NULL true
c.equals(0) = true
c == NULL false
This way you can always test for failed conversion but still work with the results as Integer instances. You might also want to tweak the number NULL represents (≠ 0).
You could roll your own, but it's just as easy to use commons lang's StringUtils.isNumeric() method. It uses Character.isDigit() to iterate over each character in the String.
You shouldn't use Exceptions to validate your values.
For single character there is a simple solution:
Character.isDigit()
For longer values it's better to use some utils. NumberUtils provided by Apache would work perfectly here:
NumberUtils.isNumber()
Please check https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/math/NumberUtils.html

Categories

Resources