001package components.utilities; 002 003/** 004 * {@code FormatChecker} utility class with methods to check whether a 005 * {@code String} can be parsed as one of the primitive types ({@code int}, 006 * {@code long}, {@code double}, or {@code boolean}). 007 */ 008public final class FormatChecker { 009 010 /* 011 * Private members -------------------------------------------------------- 012 */ 013 014 /** 015 * No-argument constructor--private to prevent instantiation. 016 */ 017 private FormatChecker() { 018 // no code needed here 019 } 020 021 /* 022 * Public members --------------------------------------------------------- 023 */ 024 025 /** 026 * Checks whether the given {@code String} represents a valid integer value 027 * in the range Integer.MIN_VALUE..Integer.MAX_VALUE. 028 * 029 * @param s 030 * the {@code String} to be checked 031 * @return true if the given {@code String} represents a valid integer, 032 * false otherwise 033 * @ensures canParseInt = [the given String represents a valid integer] 034 */ 035 public static boolean canParseInt(String s) { 036 assert s != null : "Violation of: s is not null"; 037 try { 038 Integer.parseInt(s); 039 return true; 040 } catch (NumberFormatException e) { 041 return false; 042 } 043 } 044 045 /** 046 * Checks whether the given {@code String} represents a valid integer value 047 * in the range Long.MIN_VALUE..Long.MAX_VALUE. 048 * 049 * @param s 050 * the {@code String} to be checked 051 * @return true if the given {@code String} represents a valid integer, 052 * false otherwise 053 * @ensures canParseLong = [the given String represents a valid integer] 054 */ 055 public static boolean canParseLong(String s) { 056 assert s != null : "Violation of: s is not null"; 057 try { 058 Long.parseLong(s); 059 return true; 060 } catch (NumberFormatException e) { 061 return false; 062 } 063 } 064 065 /** 066 * Checks whether the given {@code String} represents a valid real value (as 067 * defined in {@link Double}). 068 * 069 * @param s 070 * the {@code String} to be checked 071 * @return true if the given {@code String} represents a valid real, false 072 * otherwise 073 * @ensures canParseDouble = [the given String represents a valid real] 074 */ 075 public static boolean canParseDouble(String s) { 076 assert s != null : "Violation of: s is not null"; 077 try { 078 Double.parseDouble(s); 079 return true; 080 } catch (NumberFormatException e) { 081 return false; 082 } 083 } 084 085 /** 086 * Checks whether the given {@code String} represents a valid boolean value. 087 * 088 * @param s 089 * the {@code String} to be checked 090 * @return true if the given {@code String} represents a valid boolean, 091 * false otherwise 092 * @ensures canParseBoolean = (s = "true") or (s = "false") 093 */ 094 public static boolean canParseBoolean(String s) { 095 assert s != null : "Violation of: s is not null"; 096 return s.equals("true") || s.equals("false"); 097 } 098 099}