KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > commons > lang > math > NumberUtils


1 /*
2  * Copyright 2002-2005 The Apache Software Foundation.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16 package org.apache.commons.lang.math;
17
18 import java.math.BigDecimal JavaDoc;
19 import java.math.BigInteger JavaDoc;
20
21 import org.apache.commons.lang.StringUtils;
22
23 /**
24  * <p>Provides extra functionality for Java Number classes.</p>
25  *
26  * @author <a HREF="mailto:bayard@generationjava.com">Henri Yandell</a>
27  * @author <a HREF="mailto:rand_mcneely@yahoo.com">Rand McNeely</a>
28  * @author Stephen Colebourne
29  * @author <a HREF="mailto:steve.downey@netfolio.com">Steve Downey</a>
30  * @author Eric Pugh
31  * @author Phil Steitz
32  * @author Matthew Hawthorne
33  * @author <a HREF="mailto:ggregory@seagullsw.com">Gary Gregory</a>
34  * @author <a HREF="mailto:fredrik@westermarck.com">Fredrik Westermarck</a>
35  * @since 2.0
36  * @version $Id: NumberUtils.java 161243 2005-04-14 04:30:28Z ggregory $
37  */

38 public class NumberUtils {
39     
40     /** Reusable Long constant for zero. */
41     public static final Long JavaDoc LONG_ZERO = new Long JavaDoc(0L);
42     /** Reusable Long constant for one. */
43     public static final Long JavaDoc LONG_ONE = new Long JavaDoc(1L);
44     /** Reusable Long constant for minus one. */
45     public static final Long JavaDoc LONG_MINUS_ONE = new Long JavaDoc(-1L);
46     /** Reusable Integer constant for zero. */
47     public static final Integer JavaDoc INTEGER_ZERO = new Integer JavaDoc(0);
48     /** Reusable Integer constant for one. */
49     public static final Integer JavaDoc INTEGER_ONE = new Integer JavaDoc(1);
50     /** Reusable Integer constant for minus one. */
51     public static final Integer JavaDoc INTEGER_MINUS_ONE = new Integer JavaDoc(-1);
52     /** Reusable Short constant for zero. */
53     public static final Short JavaDoc SHORT_ZERO = new Short JavaDoc((short) 0);
54     /** Reusable Short constant for one. */
55     public static final Short JavaDoc SHORT_ONE = new Short JavaDoc((short) 1);
56     /** Reusable Short constant for minus one. */
57     public static final Short JavaDoc SHORT_MINUS_ONE = new Short JavaDoc((short) -1);
58     /** Reusable Byte constant for zero. */
59     public static final Byte JavaDoc BYTE_ZERO = new Byte JavaDoc((byte) 0);
60     /** Reusable Byte constant for one. */
61     public static final Byte JavaDoc BYTE_ONE = new Byte JavaDoc((byte) 1);
62     /** Reusable Byte constant for minus one. */
63     public static final Byte JavaDoc BYTE_MINUS_ONE = new Byte JavaDoc((byte) -1);
64     /** Reusable Double constant for zero. */
65     public static final Double JavaDoc DOUBLE_ZERO = new Double JavaDoc(0.0d);
66     /** Reusable Double constant for one. */
67     public static final Double JavaDoc DOUBLE_ONE = new Double JavaDoc(1.0d);
68     /** Reusable Double constant for minus one. */
69     public static final Double JavaDoc DOUBLE_MINUS_ONE = new Double JavaDoc(-1.0d);
70     /** Reusable Float constant for zero. */
71     public static final Float JavaDoc FLOAT_ZERO = new Float JavaDoc(0.0f);
72     /** Reusable Float constant for one. */
73     public static final Float JavaDoc FLOAT_ONE = new Float JavaDoc(1.0f);
74     /** Reusable Float constant for minus one. */
75     public static final Float JavaDoc FLOAT_MINUS_ONE = new Float JavaDoc(-1.0f);
76
77     /**
78      * <p><code>NumberUtils</code> instances should NOT be constructed in standard programming.
79      * Instead, the class should be used as <code>NumberUtils.stringToInt("6");</code>.</p>
80      *
81      * <p>This constructor is public to permit tools that require a JavaBean instance
82      * to operate.</p>
83      */

84     public NumberUtils() {
85     }
86
87     //-----------------------------------------------------------------------
88
/**
89      * <p>Convert a <code>String</code> to an <code>int</code>, returning
90      * <code>zero</code> if the conversion fails.</p>
91      *
92      * <p>If the string is <code>null</code>, <code>zero</code> is returned.</p>
93      *
94      * <pre>
95      * NumberUtils.stringToInt(null) = 0
96      * NumberUtils.stringToInt("") = 0
97      * NumberUtils.stringToInt("1") = 1
98      * </pre>
99      *
100      * @param str the string to convert, may be null
101      * @return the int represented by the string, or <code>zero</code> if
102      * conversion fails
103      * @deprecated Use {@link #toInt(String)}
104      * This method will be removed in Commons Lang 3.0
105      */

106     public static int stringToInt(String JavaDoc str) {
107         return toInt(str);
108     }
109
110     /**
111      * <p>Convert a <code>String</code> to an <code>int</code>, returning
112      * <code>zero</code> if the conversion fails.</p>
113      *
114      * <p>If the string is <code>null</code>, <code>zero</code> is returned.</p>
115      *
116      * <pre>
117      * NumberUtils.toInt(null) = 0
118      * NumberUtils.toInt("") = 0
119      * NumberUtils.toInt("1") = 1
120      * </pre>
121      *
122      * @param str the string to convert, may be null
123      * @return the int represented by the string, or <code>zero</code> if
124      * conversion fails
125      * @since 2.1
126      */

127     public static int toInt(String JavaDoc str) {
128         return toInt(str, 0);
129     }
130
131     /**
132      * <p>Convert a <code>String</code> to an <code>int</code>, returning a
133      * default value if the conversion fails.</p>
134      *
135      * <p>If the string is <code>null</code>, the default value is returned.</p>
136      *
137      * <pre>
138      * NumberUtils.stringToInt(null, 1) = 1
139      * NumberUtils.stringToInt("", 1) = 1
140      * NumberUtils.stringToInt("1", 0) = 1
141      * </pre>
142      *
143      * @param str the string to convert, may be null
144      * @param defaultValue the default value
145      * @return the int represented by the string, or the default if conversion fails
146      * @deprecated Use {@link #toInt(String, int)}
147      * This method will be removed in Commons Lang 3.0
148      */

149     public static int stringToInt(String JavaDoc str, int defaultValue) {
150         return toInt(str, defaultValue);
151     }
152
153     /**
154      * <p>Convert a <code>String</code> to an <code>int</code>, returning a
155      * default value if the conversion fails.</p>
156      *
157      * <p>If the string is <code>null</code>, the default value is returned.</p>
158      *
159      * <pre>
160      * NumberUtils.toInt(null, 1) = 1
161      * NumberUtils.toInt("", 1) = 1
162      * NumberUtils.toInt("1", 0) = 1
163      * </pre>
164      *
165      * @param str the string to convert, may be null
166      * @param defaultValue the default value
167      * @return the int represented by the string, or the default if conversion fails
168      * @since 2.1
169      */

170     public static int toInt(String JavaDoc str, int defaultValue) {
171         if(str == null) {
172             return defaultValue;
173         }
174         try {
175             return Integer.parseInt(str);
176         } catch (NumberFormatException JavaDoc nfe) {
177             return defaultValue;
178         }
179     }
180
181     /**
182      * <p>Convert a <code>String</code> to a <code>long</code>, returning
183      * <code>zero</code> if the conversion fails.</p>
184      *
185      * <p>If the string is <code>null</code>, <code>zero</code> is returned.</p>
186      *
187      * <pre>
188      * NumberUtils.toLong(null) = 0L
189      * NumberUtils.toLong("") = 0L
190      * NumberUtils.toLong("1") = 1L
191      * </pre>
192      *
193      * @param str the string to convert, may be null
194      * @return the long represented by the string, or <code>0</code> if
195      * conversion fails
196      * @since 2.1
197      */

198     public static long toLong(String JavaDoc str) {
199         return toLong(str, 0L);
200     }
201
202     /**
203      * <p>Convert a <code>String</code> to a <code>long</code>, returning a
204      * default value if the conversion fails.</p>
205      *
206      * <p>If the string is <code>null</code>, the default value is returned.</p>
207      *
208      * <pre>
209      * NumberUtils.toLong(null, 1L) = 1L
210      * NumberUtils.toLong("", 1L) = 1L
211      * NumberUtils.toLong("1", 0L) = 1L
212      * </pre>
213      *
214      * @param str the string to convert, may be null
215      * @param defaultValue the default value
216      * @return the long represented by the string, or the default if conversion fails
217      * @since 2.1
218      */

219     public static long toLong(String JavaDoc str, long defaultValue) {
220         if (str == null) {
221             return defaultValue;
222         }
223         try {
224             return Long.parseLong(str);
225         } catch (NumberFormatException JavaDoc nfe) {
226             return defaultValue;
227         }
228     }
229
230     /**
231      * <p>Convert a <code>String</code> to a <code>float</code>, returning
232      * <code>0.0f</code> if the conversion fails.</p>
233      *
234      * <p>If the string <code>str</code> is <code>null</code>,
235      * <code>0.0f</code> is returned.</p>
236      *
237      * <pre>
238      * NumberUtils.toFloat(null) = 0.0f
239      * NumberUtils.toFloat("") = 0.0f
240      * NumberUtils.toFloat("1.5") = 1.5f
241      * </pre>
242      *
243      * @param str the string to convert, may be <code>null</code>
244      * @return the float represented by the string, or <code>0.0f</code>
245      * if conversion fails
246      * @since 2.1
247      */

248     public static float toFloat(String JavaDoc str) {
249         return toFloat(str, 0.0f);
250     }
251
252     /**
253      * <p>Convert a <code>String</code> to a <code>float</code>, returning a
254      * default value if the conversion fails.</p>
255      *
256      * <p>If the string <code>str</code> is <code>null</code>, the default
257      * value is returned.</p>
258      *
259      * <pre>
260      * NumberUtils.toFloat(null, 1.1f) = 1.0f
261      * NumberUtils.toFloat("", 1.1f) = 1.1f
262      * NumberUtils.toFloat("1.5", 0.0f) = 1.5f
263      * </pre>
264      *
265      * @param str the string to convert, may be <code>null</code>
266      * @param defaultValue the default value
267      * @return the float represented by the string, or defaultValue
268      * if conversion fails
269      * @since 2.1
270      */

271     public static float toFloat(String JavaDoc str, float defaultValue) {
272       if (str == null) {
273           return defaultValue;
274       }
275       try {
276           return Float.parseFloat(str);
277       } catch (NumberFormatException JavaDoc nfe) {
278           return defaultValue;
279       }
280     }
281
282     /**
283      * <p>Convert a <code>String</code> to a <code>double</code>, returning
284      * <code>0.0d</code> if the conversion fails.</p>
285      *
286      * <p>If the string <code>str</code> is <code>null</code>,
287      * <code>0.0d</code> is returned.</p>
288      *
289      * <pre>
290      * NumberUtils.toDouble(null) = 0.0d
291      * NumberUtils.toDouble("") = 0.0d
292      * NumberUtils.toDouble("1.5") = 1.5d
293      * </pre>
294      *
295      * @param str the string to convert, may be <code>null</code>
296      * @return the double represented by the string, or <code>0.0d</code>
297      * if conversion fails
298      * @since 2.1
299      */

300     public static double toDouble(String JavaDoc str) {
301         return toDouble(str, 0.0d);
302     }
303
304     /**
305      * <p>Convert a <code>String</code> to a <code>double</code>, returning a
306      * default value if the conversion fails.</p>
307      *
308      * <p>If the string <code>str</code> is <code>null</code>, the default
309      * value is returned.</p>
310      *
311      * <pre>
312      * NumberUtils.toDouble(null, 1.1d) = 1.1d
313      * NumberUtils.toDouble("", 1.1d) = 1.1d
314      * NumberUtils.toDouble("1.5", 0.0d) = 1.5d
315      * </pre>
316      *
317      * @param str the string to convert, may be <code>null</code>
318      * @param defaultValue the default value
319      * @return the double represented by the string, or defaultValue
320      * if conversion fails
321      * @since 2.1
322      */

323     public static double toDouble(String JavaDoc str, double defaultValue) {
324       if (str == null) {
325           return defaultValue;
326       }
327       try {
328           return Double.parseDouble(str);
329       } catch (NumberFormatException JavaDoc nfe) {
330           return defaultValue;
331       }
332     }
333
334     //-----------------------------------------------------------------------
335
// must handle Long, Float, Integer, Float, Short,
336
// BigDecimal, BigInteger and Byte
337
// useful methods:
338
// Byte.decode(String)
339
// Byte.valueOf(String,int radix)
340
// Byte.valueOf(String)
341
// Double.valueOf(String)
342
// Float.valueOf(String)
343
// new Float(String)
344
// Integer.valueOf(String,int radix)
345
// Integer.valueOf(String)
346
// Integer.decode(String)
347
// Integer.getInteger(String)
348
// Integer.getInteger(String,int val)
349
// Integer.getInteger(String,Integer val)
350
// new Integer(String)
351
// new Double(String)
352
// new Byte(String)
353
// new Long(String)
354
// Long.getLong(String)
355
// Long.getLong(String,int)
356
// Long.getLong(String,Integer)
357
// Long.valueOf(String,int)
358
// Long.valueOf(String)
359
// new Short(String)
360
// Short.decode(String)
361
// Short.valueOf(String,int)
362
// Short.valueOf(String)
363
// new BigDecimal(String)
364
// new BigInteger(String)
365
// new BigInteger(String,int radix)
366
// Possible inputs:
367
// 45 45.5 45E7 4.5E7 Hex Oct Binary xxxF xxxD xxxf xxxd
368
// plus minus everything. Prolly more. A lot are not separable.
369

370     /**
371      * <p>Turns a string value into a java.lang.Number.</p>
372      *
373      * <p>First, the value is examined for a type qualifier on the end
374      * (<code>'f','F','d','D','l','L'</code>). If it is found, it starts
375      * trying to create successively larger types from the type specified
376      * until one is found that can represent the value.</p>
377      *
378      * <p>If a type specifier is not found, it will check for a decimal point
379      * and then try successively larger types from <code>Integer</code> to
380      * <code>BigInteger</code> and from <code>Float</code> to
381      * <code>BigDecimal</code>.</p>
382      *
383      * <p>If the string starts with <code>0x</code> or <code>-0x</code>, it
384      * will be interpreted as a hexadecimal integer. Values with leading
385      * <code>0</code>'s will not be interpreted as octal.</p>
386      *
387      * <p>Returns <code>null</code> if the string is <code>null</code>.</p>
388      *
389      * <p>This method does not trim the input string, i.e., strings with leading
390      * or trailing spaces will generate NumberFormatExceptions.</p>
391      *
392      * @param str String containing a number, may be null
393      * @return Number created from the string
394      * @throws NumberFormatException if the value cannot be converted
395      */

396     public static Number JavaDoc createNumber(String JavaDoc str) throws NumberFormatException JavaDoc {
397         if (str == null) {
398             return null;
399         }
400         if (StringUtils.isBlank(str)) {
401             throw new NumberFormatException JavaDoc("A blank string is not a valid number");
402         }
403         if (str.startsWith("--")) {
404             // this is protection for poorness in java.lang.BigDecimal.
405
// it accepts this as a legal value, but it does not appear
406
// to be in specification of class. OS X Java parses it to
407
// a wrong value.
408
return null;
409         }
410         if (str.startsWith("0x") || str.startsWith("-0x")) {
411             return createInteger(str);
412         }
413         char lastChar = str.charAt(str.length() - 1);
414         String JavaDoc mant;
415         String JavaDoc dec;
416         String JavaDoc exp;
417         int decPos = str.indexOf('.');
418         int expPos = str.indexOf('e') + str.indexOf('E') + 1;
419
420         if (decPos > -1) {
421
422             if (expPos > -1) {
423                 if (expPos < decPos) {
424                     throw new NumberFormatException JavaDoc(str + " is not a valid number.");
425                 }
426                 dec = str.substring(decPos + 1, expPos);
427             } else {
428                 dec = str.substring(decPos + 1);
429             }
430             mant = str.substring(0, decPos);
431         } else {
432             if (expPos > -1) {
433                 mant = str.substring(0, expPos);
434             } else {
435                 mant = str;
436             }
437             dec = null;
438         }
439         if (!Character.isDigit(lastChar)) {
440             if (expPos > -1 && expPos < str.length() - 1) {
441                 exp = str.substring(expPos + 1, str.length() - 1);
442             } else {
443                 exp = null;
444             }
445             //Requesting a specific type..
446
String JavaDoc numeric = str.substring(0, str.length() - 1);
447             boolean allZeros = isAllZeros(mant) && isAllZeros(exp);
448             switch (lastChar) {
449                 case 'l' :
450                 case 'L' :
451                     if (dec == null
452                         && exp == null
453                         && isDigits(numeric.substring(1))
454                         && (numeric.charAt(0) == '-' || Character.isDigit(numeric.charAt(0)))) {
455                         try {
456                             return createLong(numeric);
457                         } catch (NumberFormatException JavaDoc nfe) {
458                             //Too big for a long
459
}
460                         return createBigInteger(numeric);
461
462                     }
463                     throw new NumberFormatException JavaDoc(str + " is not a valid number.");
464                 case 'f' :
465                 case 'F' :
466                     try {
467                         Float JavaDoc f = NumberUtils.createFloat(numeric);
468                         if (!(f.isInfinite() || (f.floatValue() == 0.0F && !allZeros))) {
469                             //If it's too big for a float or the float value = 0 and the string
470
//has non-zeros in it, then float does not have the precision we want
471
return f;
472                         }
473
474                     } catch (NumberFormatException JavaDoc nfe) {
475                     }
476                     //Fall through
477
case 'd' :
478                 case 'D' :
479                     try {
480                         Double JavaDoc d = NumberUtils.createDouble(numeric);
481                         if (!(d.isInfinite() || (d.floatValue() == 0.0D && !allZeros))) {
482                             return d;
483                         }
484                     } catch (NumberFormatException JavaDoc nfe) {
485                     }
486                     try {
487                         return createBigDecimal(numeric);
488                     } catch (NumberFormatException JavaDoc e) {
489                     }
490                     //Fall through
491
default :
492                     throw new NumberFormatException JavaDoc(str + " is not a valid number.");
493
494             }
495         } else {
496             //User doesn't have a preference on the return type, so let's start
497
//small and go from there...
498
if (expPos > -1 && expPos < str.length() - 1) {
499                 exp = str.substring(expPos + 1, str.length());
500             } else {
501                 exp = null;
502             }
503             if (dec == null && exp == null) {
504                 //Must be an int,long,bigint
505
try {
506                     return createInteger(str);
507                 } catch (NumberFormatException JavaDoc nfe) {
508                 }
509                 try {
510                     return createLong(str);
511                 } catch (NumberFormatException JavaDoc nfe) {
512                 }
513                 return createBigInteger(str);
514
515             } else {
516                 //Must be a float,double,BigDec
517
boolean allZeros = isAllZeros(mant) && isAllZeros(exp);
518                 try {
519                     Float JavaDoc f = createFloat(str);
520                     if (!(f.isInfinite() || (f.floatValue() == 0.0F && !allZeros))) {
521                         return f;
522                     }
523                 } catch (NumberFormatException JavaDoc nfe) {
524                 }
525                 try {
526                     Double JavaDoc d = createDouble(str);
527                     if (!(d.isInfinite() || (d.doubleValue() == 0.0D && !allZeros))) {
528                         return d;
529                     }
530                 } catch (NumberFormatException JavaDoc nfe) {
531                 }
532
533                 return createBigDecimal(str);
534
535             }
536         }
537     }
538
539     /**
540      * <p>Utility method for {@link #createNumber(java.lang.String)}.</p>
541      *
542      * <p>Returns <code>true</code> if s is <code>null</code>.</p>
543      *
544      * @param str the String to check
545      * @return if it is all zeros or <code>null</code>
546      */

547     private static boolean isAllZeros(String JavaDoc str) {
548         if (str == null) {
549             return true;
550         }
551         for (int i = str.length() - 1; i >= 0; i--) {
552             if (str.charAt(i) != '0') {
553                 return false;
554             }
555         }
556         return str.length() > 0;
557     }
558
559     //-----------------------------------------------------------------------
560
/**
561      * <p>Convert a <code>String</code> to a <code>Float</code>.</p>
562      *
563      * <p>Returns <code>null</code> if the string is <code>null</code>.</p>
564      *
565      * @param str a <code>String</code> to convert, may be null
566      * @return converted <code>Float</code>
567      * @throws NumberFormatException if the value cannot be converted
568      */

569     public static Float JavaDoc createFloat(String JavaDoc str) {
570         if (str == null) {
571             return null;
572         }
573         return Float.valueOf(str);
574     }
575
576     /**
577      * <p>Convert a <code>String</code> to a <code>Double</code>.</p>
578      *
579      * <p>Returns <code>null</code> if the string is <code>null</code>.</p>
580      *
581      * @param str a <code>String</code> to convert, may be null
582      * @return converted <code>Double</code>
583      * @throws NumberFormatException if the value cannot be converted
584      */

585     public static Double JavaDoc createDouble(String JavaDoc str) {
586         if (str == null) {
587             return null;
588         }
589         return Double.valueOf(str);
590     }
591
592     /**
593      * <p>Convert a <code>String</code> to a <code>Integer</code>, handling
594      * hex and octal notations.</p>
595      *
596      * <p>Returns <code>null</code> if the string is <code>null</code>.</p>
597      *
598      * @param str a <code>String</code> to convert, may be null
599      * @return converted <code>Integer</code>
600      * @throws NumberFormatException if the value cannot be converted
601      */

602     public static Integer JavaDoc createInteger(String JavaDoc str) {
603         if (str == null) {
604             return null;
605         }
606         // decode() handles 0xAABD and 0777 (hex and octal) as well.
607
return Integer.decode(str);
608     }
609
610     /**
611      * <p>Convert a <code>String</code> to a <code>Long</code>.</p>
612      *
613      * <p>Returns <code>null</code> if the string is <code>null</code>.</p>
614      *
615      * @param str a <code>String</code> to convert, may be null
616      * @return converted <code>Long</code>
617      * @throws NumberFormatException if the value cannot be converted
618      */

619     public static Long JavaDoc createLong(String JavaDoc str) {
620         if (str == null) {
621             return null;
622         }
623         return Long.valueOf(str);
624     }
625
626     /**
627      * <p>Convert a <code>String</code> to a <code>BigInteger</code>.</p>
628      *
629      * <p>Returns <code>null</code> if the string is <code>null</code>.</p>
630      *
631      * @param str a <code>String</code> to convert, may be null
632      * @return converted <code>BigInteger</code>
633      * @throws NumberFormatException if the value cannot be converted
634      */

635     public static BigInteger JavaDoc createBigInteger(String JavaDoc str) {
636         if (str == null) {
637             return null;
638         }
639         return new BigInteger JavaDoc(str);
640     }
641
642     /**
643      * <p>Convert a <code>String</code> to a <code>BigDecimal</code>.</p>
644      *
645      * <p>Returns <code>null</code> if the string is <code>null</code>.</p>
646      *
647      * @param str a <code>String</code> to convert, may be null
648      * @return converted <code>BigDecimal</code>
649      * @throws NumberFormatException if the value cannot be converted
650      */

651     public static BigDecimal JavaDoc createBigDecimal(String JavaDoc str) {
652         if (str == null) {
653             return null;
654         }
655         // handle JDK1.3.1 bug where "" throws IndexOutOfBoundsException
656
if (StringUtils.isBlank(str)) {
657             throw new NumberFormatException JavaDoc("A blank string is not a valid number");
658         }
659         return new BigDecimal JavaDoc(str);
660     }
661
662     // Min in array
663
//--------------------------------------------------------------------
664
/**
665      * <p>Returns the minimum value in an array.</p>
666      *
667      * @param array an array, must not be null or empty
668      * @return the minimum value in the array
669      * @throws IllegalArgumentException if <code>array</code> is <code>null</code>
670      * @throws IllegalArgumentException if <code>array</code> is empty
671      */

672     public static long min(long[] array) {
673         // Validates input
674
if (array == null) {
675             throw new IllegalArgumentException JavaDoc("The Array must not be null");
676         } else if (array.length == 0) {
677             throw new IllegalArgumentException JavaDoc("Array cannot be empty.");
678         }
679     
680         // Finds and returns min
681
long min = array[0];
682         for (int i = 1; i < array.length; i++) {
683             if (array[i] < min) {
684                 min = array[i];
685             }
686         }
687     
688         return min;
689     }
690
691     /**
692      * <p>Returns the minimum value in an array.</p>
693      *
694      * @param array an array, must not be null or empty
695      * @return the minimum value in the array
696      * @throws IllegalArgumentException if <code>array</code> is <code>null</code>
697      * @throws IllegalArgumentException if <code>array</code> is empty
698      */

699     public static int min(int[] array) {
700         // Validates input
701
if (array == null) {
702             throw new IllegalArgumentException JavaDoc("The Array must not be null");
703         } else if (array.length == 0) {
704             throw new IllegalArgumentException JavaDoc("Array cannot be empty.");
705         }
706     
707         // Finds and returns min
708
int min = array[0];
709         for (int j = 1; j < array.length; j++) {
710             if (array[j] < min) {
711                 min = array[j];
712             }
713         }
714     
715         return min;
716     }
717
718     /**
719      * <p>Returns the minimum value in an array.</p>
720      *
721      * @param array an array, must not be null or empty
722      * @return the minimum value in the array
723      * @throws IllegalArgumentException if <code>array</code> is <code>null</code>
724      * @throws IllegalArgumentException if <code>array</code> is empty
725      */

726     public static short min(short[] array) {
727         // Validates input
728
if (array == null) {
729             throw new IllegalArgumentException JavaDoc("The Array must not be null");
730         } else if (array.length == 0) {
731             throw new IllegalArgumentException JavaDoc("Array cannot be empty.");
732         }
733     
734         // Finds and returns min
735
short min = array[0];
736         for (int i = 1; i < array.length; i++) {
737             if (array[i] < min) {
738                 min = array[i];
739             }
740         }
741     
742         return min;
743     }
744
745      /**
746      * <p>Returns the minimum value in an array.</p>
747      *
748      * @param array an array, must not be null or empty
749      * @return the minimum value in the array
750      * @throws IllegalArgumentException if <code>array</code> is <code>null</code>
751      * @throws IllegalArgumentException if <code>array</code> is empty
752      */

753     public static double min(double[] array) {
754         // Validates input
755
if (array == null) {
756             throw new IllegalArgumentException JavaDoc("The Array must not be null");
757         } else if (array.length == 0) {
758             throw new IllegalArgumentException JavaDoc("Array cannot be empty.");
759         }
760     
761         // Finds and returns min
762
double min = array[0];
763         for (int i = 1; i < array.length; i++) {
764             if (array[i] < min) {
765                 min = array[i];
766             }
767         }
768     
769         return min;
770     }
771
772     /**
773      * <p>Returns the minimum value in an array.</p>
774      *
775      * @param array an array, must not be null or empty
776      * @return the minimum value in the array
777      * @throws IllegalArgumentException if <code>array</code> is <code>null</code>
778      * @throws IllegalArgumentException if <code>array</code> is empty
779      */

780     public static float min(float[] array) {
781         // Validates input
782
if (array == null) {
783             throw new IllegalArgumentException JavaDoc("The Array must not be null");
784         } else if (array.length == 0) {
785             throw new IllegalArgumentException JavaDoc("Array cannot be empty.");
786         }
787     
788         // Finds and returns min
789
float min = array[0];
790         for (int i = 1; i < array.length; i++) {
791             if (array[i] < min) {
792                 min = array[i];
793             }
794         }
795     
796         return min;
797     }
798
799     // Max in array
800
//--------------------------------------------------------------------
801
/**
802      * <p>Returns the maximum value in an array.</p>
803      *
804      * @param array an array, must not be null or empty
805      * @return the minimum value in the array
806      * @throws IllegalArgumentException if <code>array</code> is <code>null</code>
807      * @throws IllegalArgumentException if <code>array</code> is empty
808      */

809     public static long max(long[] array) {
810         // Validates input
811
if (array == null) {
812             throw new IllegalArgumentException JavaDoc("The Array must not be null");
813         } else if (array.length == 0) {
814             throw new IllegalArgumentException JavaDoc("Array cannot be empty.");
815         }
816
817         // Finds and returns max
818
long max = array[0];
819         for (int j = 1; j < array.length; j++) {
820             if (array[j] > max) {
821                 max = array[j];
822             }
823         }
824
825         return max;
826     }
827
828     /**
829      * <p>Returns the maximum value in an array.</p>
830      *
831      * @param array an array, must not be null or empty
832      * @return the minimum value in the array
833      * @throws IllegalArgumentException if <code>array</code> is <code>null</code>
834      * @throws IllegalArgumentException if <code>array</code> is empty
835      */

836     public static int max(int[] array) {
837         // Validates input
838
if (array == null) {
839             throw new IllegalArgumentException JavaDoc("The Array must not be null");
840         } else if (array.length == 0) {
841             throw new IllegalArgumentException JavaDoc("Array cannot be empty.");
842         }
843     
844         // Finds and returns max
845
int max = array[0];
846         for (int j = 1; j < array.length; j++) {
847             if (array[j] > max) {
848                 max = array[j];
849             }
850         }
851     
852         return max;
853     }
854
855     /**
856      * <p>Returns the maximum value in an array.</p>
857      *
858      * @param array an array, must not be null or empty
859      * @return the minimum value in the array
860      * @throws IllegalArgumentException if <code>array</code> is <code>null</code>
861      * @throws IllegalArgumentException if <code>array</code> is empty
862      */

863     public static short max(short[] array) {
864         // Validates input
865
if (array == null) {
866             throw new IllegalArgumentException JavaDoc("The Array must not be null");
867         } else if (array.length == 0) {
868             throw new IllegalArgumentException JavaDoc("Array cannot be empty.");
869         }
870     
871         // Finds and returns max
872
short max = array[0];
873         for (int i = 1; i < array.length; i++) {
874             if (array[i] > max) {
875                 max = array[i];
876             }
877         }
878     
879         return max;
880     }
881
882     /**
883      * <p>Returns the maximum value in an array.</p>
884      *
885      * @param array an array, must not be null or empty
886      * @return the minimum value in the array
887      * @throws IllegalArgumentException if <code>array</code> is <code>null</code>
888      * @throws IllegalArgumentException if <code>array</code> is empty
889      */

890     public static double max(double[] array) {
891         // Validates input
892
if (array== null) {
893             throw new IllegalArgumentException JavaDoc("The Array must not be null");
894         } else if (array.length == 0) {
895             throw new IllegalArgumentException JavaDoc("Array cannot be empty.");
896         }
897     
898         // Finds and returns max
899
double max = array[0];
900         for (int j = 1; j < array.length; j++) {
901             if (array[j] > max) {
902                 max = array[j];
903             }
904         }
905     
906         return max;
907     }
908
909     /**
910      * <p>Returns the maximum value in an array.</p>
911      *
912      * @param array an array, must not be null or empty
913      * @return the minimum value in the array
914      * @throws IllegalArgumentException if <code>array</code> is <code>null</code>
915      * @throws IllegalArgumentException if <code>array</code> is empty
916      */

917     public static float max(float[] array) {
918         // Validates input
919
if (array == null) {
920             throw new IllegalArgumentException JavaDoc("The Array must not be null");
921         } else if (array.length == 0) {
922             throw new IllegalArgumentException JavaDoc("Array cannot be empty.");
923         }
924
925         // Finds and returns max
926
float max = array[0];
927         for (int j = 1; j < array.length; j++) {
928             if (array[j] > max) {
929                 max = array[j];
930             }
931         }
932
933         return max;
934     }
935      
936     // 3 param min
937
//-----------------------------------------------------------------------
938
/**
939      * <p>Gets the minimum of three <code>long</code> values.</p>
940      *
941      * @param a value 1
942      * @param b value 2
943      * @param c value 3
944      * @return the smallest of the values
945      */

946     public static long min(long a, long b, long c) {
947         if (b < a) {
948             a = b;
949         }
950         if (c < a) {
951             a = c;
952         }
953         return a;
954     }
955
956     /**
957      * <p>Gets the minimum of three <code>int</code> values.</p>
958      *
959      * @param a value 1
960      * @param b value 2
961      * @param c value 3
962      * @return the smallest of the values
963      */

964     public static int min(int a, int b, int c) {
965         if (b < a) {
966             a = b;
967         }
968         if (c < a) {
969             a = c;
970         }
971         return a;
972     }
973
974     /**
975      * <p>Gets the minimum of three <code>short</code> values.</p>
976      *
977      * @param a value 1
978      * @param b value 2
979      * @param c value 3
980      * @return the smallest of the values
981      */

982     public static short min(short a, short b, short c) {
983         if (b < a) {
984             a = b;
985         }
986         if (c < a) {
987             a = c;
988         }
989         return a;
990     }
991
992     /**
993      * <p>Gets the minimum of three <code>byte</code> values.</p>
994      *
995      * @param a value 1
996      * @param b value 2
997      * @param c value 3
998      * @return the smallest of the values
999      */

1000    public static byte min(byte a, byte b, byte c) {
1001        if (b < a) {
1002            a = b;
1003        }
1004        if (c < a) {
1005            a = c;
1006        }
1007        return a;
1008    }
1009
1010    /**
1011     * <p>Gets the minimum of three <code>double</code> values.</p>
1012     *
1013     * <p>If any value is <code>NaN</code>, <code>NaN</code> is
1014     * returned. Infinity is handled.</p>
1015     *
1016     * @param a value 1
1017     * @param b value 2
1018     * @param c value 3
1019     * @return the smallest of the values
1020     */

1021    public static double min(double a, double b, double c) {
1022        return Math.min(Math.min(a, b), c);
1023    }
1024
1025    /**
1026     * <p>Gets the minimum of three <code>float</code> values.</p>
1027     *
1028     * <p>If any value is <code>NaN</code>, <code>NaN</code> is
1029     * returned. Infinity is handled.</p>
1030     *
1031     * @param a value 1
1032     * @param b value 2
1033     * @param c value 3
1034     * @return the smallest of the values
1035     */

1036    public static float min(float a, float b, float c) {
1037        return Math.min(Math.min(a, b), c);
1038    }
1039
1040    // 3 param max
1041
//-----------------------------------------------------------------------
1042
/**
1043     * <p>Gets the maximum of three <code>long</code> values.</p>
1044     *
1045     * @param a value 1
1046     * @param b value 2
1047     * @param c value 3
1048     * @return the largest of the values
1049     */

1050    public static long max(long a, long b, long c) {
1051        if (b > a) {
1052            a = b;
1053        }
1054        if (c > a) {
1055            a = c;
1056        }
1057        return a;
1058    }
1059
1060    /**
1061     * <p>Gets the maximum of three <code>int</code> values.</p>
1062     *
1063     * @param a value 1
1064     * @param b value 2
1065     * @param c value 3
1066     * @return the largest of the values
1067     */

1068    public static int max(int a, int b, int c) {
1069        if (b > a) {
1070            a = b;
1071        }
1072        if (c > a) {
1073            a = c;
1074        }
1075        return a;
1076    }
1077
1078    /**
1079     * <p>Gets the maximum of three <code>short</code> values.</p>
1080     *
1081     * @param a value 1
1082     * @param b value 2
1083     * @param c value 3
1084     * @return the largest of the values
1085     */

1086    public static short max(short a, short b, short c) {
1087        if (b > a) {
1088            a = b;
1089        }
1090        if (c > a) {
1091            a = c;
1092        }
1093        return a;
1094    }
1095
1096    /**
1097     * <p>Gets the maximum of three <code>byte</code> values.</p>
1098     *
1099     * @param a value 1
1100     * @param b value 2
1101     * @param c value 3
1102     * @return the largest of the values
1103     */

1104    public static byte max(byte a, byte b, byte c) {
1105        if (b > a) {
1106            a = b;
1107        }
1108        if (c > a) {
1109            a = c;
1110        }
1111        return a;
1112    }
1113
1114    /**
1115     * <p>Gets the maximum of three <code>double</code> values.</p>
1116     *
1117     * <p>If any value is <code>NaN</code>, <code>NaN</code> is
1118     * returned. Infinity is handled.</p>
1119     *
1120     * @param a value 1
1121     * @param b value 2
1122     * @param c value 3
1123     * @return the largest of the values
1124     */

1125    public static double max(double a, double b, double c) {
1126        return Math.max(Math.max(a, b), c);
1127    }
1128
1129    /**
1130     * <p>Gets the maximum of three <code>float</code> values.</p>
1131     *
1132     * <p>If any value is <code>NaN</code>, <code>NaN</code> is
1133     * returned. Infinity is handled.</p>
1134     *
1135     * @param a value 1
1136     * @param b value 2
1137     * @param c value 3
1138     * @return the largest of the values
1139     */

1140    public static float max(float a, float b, float c) {
1141        return Math.max(Math.max(a, b), c);
1142    }
1143
1144    //-----------------------------------------------------------------------
1145
/**
1146     * <p>Compares two <code>doubles</code> for order.</p>
1147     *
1148     * <p>This method is more comprehensive than the standard Java greater
1149     * than, less than and equals operators.</p>
1150     * <ul>
1151     * <li>It returns <code>-1</code> if the first value is less than the second.</li>
1152     * <li>It returns <code>+1</code> if the first value is greater than the second.</li>
1153     * <li>It returns <code>0</code> if the values are equal.</li>
1154     * </ul>
1155     *
1156     * <p>
1157     * The ordering is as follows, largest to smallest:
1158     * <ul>
1159     * <li>NaN
1160     * <li>Positive infinity
1161     * <li>Maximum double
1162     * <li>Normal positive numbers
1163     * <li>+0.0
1164     * <li>-0.0
1165     * <li>Normal negative numbers
1166     * <li>Minimum double (<code>-Double.MAX_VALUE</code>)
1167     * <li>Negative infinity
1168     * </ul>
1169     * </p>
1170     *
1171     * <p>Comparing <code>NaN</code> with <code>NaN</code> will
1172     * return <code>0</code>.</p>
1173     *
1174     * @param lhs the first <code>double</code>
1175     * @param rhs the second <code>double</code>
1176     * @return <code>-1</code> if lhs is less, <code>+1</code> if greater,
1177     * <code>0</code> if equal to rhs
1178     */

1179    public static int compare(double lhs, double rhs) {
1180        if (lhs < rhs) {
1181            return -1;
1182        }
1183        if (lhs > rhs) {
1184            return +1;
1185        }
1186        // Need to compare bits to handle 0.0 == -0.0 being true
1187
// compare should put -0.0 < +0.0
1188
// Two NaNs are also == for compare purposes
1189
// where NaN == NaN is false
1190
long lhsBits = Double.doubleToLongBits(lhs);
1191        long rhsBits = Double.doubleToLongBits(rhs);
1192        if (lhsBits == rhsBits) {
1193            return 0;
1194        }
1195        // Something exotic! A comparison to NaN or 0.0 vs -0.0
1196
// Fortunately NaN's long is > than everything else
1197
// Also negzeros bits < poszero
1198
// NAN: 9221120237041090560
1199
// MAX: 9218868437227405311
1200
// NEGZERO: -9223372036854775808
1201
if (lhsBits < rhsBits) {
1202            return -1;
1203        } else {
1204            return +1;
1205        }
1206    }
1207    
1208    /**
1209     * <p>Compares two floats for order.</p>
1210     *
1211     * <p>This method is more comprehensive than the standard Java greater than,
1212     * less than and equals operators.</p>
1213     * <ul>
1214     * <li>It returns <code>-1</code> if the first value is less than the second.
1215     * <li>It returns <code>+1</code> if the first value is greater than the second.
1216     * <li>It returns <code>0</code> if the values are equal.
1217     * </ul>
1218     *
1219     * <p> The ordering is as follows, largest to smallest:
1220     * <ul>
1221     * <li>NaN
1222     * <li>Positive infinity
1223     * <li>Maximum float
1224     * <li>Normal positive numbers
1225     * <li>+0.0
1226     * <li>-0.0
1227     * <li>Normal negative numbers
1228     * <li>Minimum float (<code>-Float.MAX_VALUE</code>)
1229     * <li>Negative infinity
1230     * </ul>
1231     *
1232     * <p>Comparing <code>NaN</code> with <code>NaN</code> will return
1233     * <code>0</code>.</p>
1234     *
1235     * @param lhs the first <code>float</code>
1236     * @param rhs the second <code>float</code>
1237     * @return <code>-1</code> if lhs is less, <code>+1</code> if greater,
1238     * <code>0</code> if equal to rhs
1239     */

1240    public static int compare(float lhs, float rhs) {
1241        if (lhs < rhs) {
1242            return -1;
1243        }
1244        if (lhs > rhs) {
1245            return +1;
1246        }
1247        //Need to compare bits to handle 0.0 == -0.0 being true
1248
// compare should put -0.0 < +0.0
1249
// Two NaNs are also == for compare purposes
1250
// where NaN == NaN is false
1251
int lhsBits = Float.floatToIntBits(lhs);
1252        int rhsBits = Float.floatToIntBits(rhs);
1253        if (lhsBits == rhsBits) {
1254            return 0;
1255        }
1256        //Something exotic! A comparison to NaN or 0.0 vs -0.0
1257
//Fortunately NaN's int is > than everything else
1258
//Also negzeros bits < poszero
1259
//NAN: 2143289344
1260
//MAX: 2139095039
1261
//NEGZERO: -2147483648
1262
if (lhsBits < rhsBits) {
1263            return -1;
1264        } else {
1265            return +1;
1266        }
1267    }
1268    
1269    //-----------------------------------------------------------------------
1270
/**
1271     * <p>Checks whether the <code>String</code> contains only
1272     * digit characters.</p>
1273     *
1274     * <p><code>Null</code> and empty String will return
1275     * <code>false</code>.</p>
1276     *
1277     * @param str the <code>String</code> to check
1278     * @return <code>true</code> if str contains only unicode numeric
1279     */

1280    public static boolean isDigits(String JavaDoc str) {
1281        if (StringUtils.isEmpty(str)) {
1282            return false;
1283        }
1284        for (int i = 0; i < str.length(); i++) {
1285            if (!Character.isDigit(str.charAt(i))) {
1286                return false;
1287            }
1288        }
1289        return true;
1290    }
1291
1292    /**
1293     * <p>Checks whether the String a valid Java number.</p>
1294     *
1295     * <p>Valid numbers include hexadecimal marked with the <code>0x</code>
1296     * qualifier, scientific notation and numbers marked with a type
1297     * qualifier (e.g. 123L).</p>
1298     *
1299     * <p><code>Null</code> and empty String will return
1300     * <code>false</code>.</p>
1301     *
1302     * @param str the <code>String</code> to check
1303     * @return <code>true</code> if the string is a correctly formatted number
1304     */

1305    public static boolean isNumber(String JavaDoc str) {
1306        if (StringUtils.isEmpty(str)) {
1307            return false;
1308        }
1309        char[] chars = str.toCharArray();
1310        int sz = chars.length;
1311        boolean hasExp = false;
1312        boolean hasDecPoint = false;
1313        boolean allowSigns = false;
1314        boolean foundDigit = false;
1315        // deal with any possible sign up front
1316
int start = (chars[0] == '-') ? 1 : 0;
1317        if (sz > start + 1) {
1318            if (chars[start] == '0' && chars[start + 1] == 'x') {
1319                int i = start + 2;
1320                if (i == sz) {
1321                    return false; // str == "0x"
1322
}
1323                // checking hex (it can't be anything else)
1324
for (; i < chars.length; i++) {
1325                    if ((chars[i] < '0' || chars[i] > '9')
1326                        && (chars[i] < 'a' || chars[i] > 'f')
1327                        && (chars[i] < 'A' || chars[i] > 'F')) {
1328                        return false;
1329                    }
1330                }
1331                return true;
1332            }
1333        }
1334        sz--; // don't want to loop to the last char, check it afterwords
1335
// for type qualifiers
1336
int i = start;
1337        // loop to the next to last char or to the last char if we need another digit to
1338
// make a valid number (e.g. chars[0..5] = "1234E")
1339
while (i < sz || (i < sz + 1 && allowSigns && !foundDigit)) {
1340            if (chars[i] >= '0' && chars[i] <= '9') {
1341                foundDigit = true;
1342                allowSigns = false;
1343
1344            } else if (chars[i] == '.') {
1345                if (hasDecPoint || hasExp) {
1346                    // two decimal points or dec in exponent
1347
return false;
1348                }
1349                hasDecPoint = true;
1350            } else if (chars[i] == 'e' || chars[i] == 'E') {
1351                // we've already taken care of hex.
1352
if (hasExp) {
1353                    // two E's
1354
return false;
1355                }
1356                if (!foundDigit) {
1357                    return false;
1358                }
1359                hasExp = true;
1360                allowSigns = true;
1361            } else if (chars[i] == '+' || chars[i] == '-') {
1362                if (!allowSigns) {
1363                    return false;
1364                }
1365                allowSigns = false;
1366                foundDigit = false; // we need a digit after the E
1367
} else {
1368                return false;
1369            }
1370            i++;
1371        }
1372        if (i < chars.length) {
1373            if (chars[i] >= '0' && chars[i] <= '9') {
1374                // no type qualifier, OK
1375
return true;
1376            }
1377            if (chars[i] == 'e' || chars[i] == 'E') {
1378                // can't have an E at the last byte
1379
return false;
1380            }
1381            if (!allowSigns
1382                && (chars[i] == 'd'
1383                    || chars[i] == 'D'
1384                    || chars[i] == 'f'
1385                    || chars[i] == 'F')) {
1386                return foundDigit;
1387            }
1388            if (chars[i] == 'l'
1389                || chars[i] == 'L') {
1390                // not allowing L with an exponent
1391
return foundDigit && !hasExp;
1392            }
1393            // last character is illegal
1394
return false;
1395        }
1396        // allowSigns is true iff the val ends in 'E'
1397
// found digit it to make sure weird stuff like '.' and '1E-' doesn't pass
1398
return !allowSigns && foundDigit;
1399    }
1400    
1401}
1402
Popular Tags