Where I am wrong? (Exception handling) - java

I can't get why my code catches exception..
I assume there is something wrong with a constructor, but I don't see where exactly..
public class OrderDate
{
private String date;
public OrderDate(String date) throws IllegalDateFormatException
{
IllegalDateFormatException wrongDate =
new IllegalDateFormatException("Date must have the following"
+ " format: dd/mm/yy");
if(date.length() > 8
|| (date.charAt(0) == 0 && date.charAt(1) == 0)
|| (date.charAt(3) == 0 && date.charAt(4) == 0)
|| (date.charAt(0) == 3 && date.charAt(1) > 1)
|| (date.charAt(3) == 1 && date.charAt(4) > 2)
|| date.charAt(2) != '/'
|| date.charAt(5) != '/'
|| date.charAt(0) > 3
|| date.charAt(3) > 1
|| !isDigit(date.charAt(0))
|| !isDigit(date.charAt(1))
|| !isDigit(date.charAt(3))
|| !isDigit(date.charAt(4))
|| !isDigit(date.charAt(6))
|| !isDigit(date.charAt(7)))
throw wrongDate;
else
this.date = date;
}
private boolean isDigit(char z)
{
return z >= '0' && z <= '9';
}
}
In the main method I use the following:
try
{
OrderDate myDate = new OrderDate("10/02/15");
System.out.println("all fine");
}
catch(Exception e)
{
System.out.println(e);
System.exit(0);
}
And the exception class:
public class IllegalDateFormatException extends Exception
{
public IllegalDateFormatException(String error)
{
super(error);
}
}
Thanks very much for help!

The reason you are throwing an exception is your large if/else block has a bug in it.
(date.charAt(0) == 0 && date.charAt(1) == 0)
|| (date.charAt(3) == 0 && date.charAt(4) == 0)
|| (date.charAt(0) == 3 && date.charAt(1) > 1)
|| (date.charAt(3) == 1 && date.charAt(4) > 2)
...
|| date.charAt(0) > 3
|| date.charAt(3) > 1
string.charAt(in) returns a character. you are checking to see if the values are ints. Since characters can be represented as integer values (like ASCII value etc) expressions like date.charAt(1) > 1 will always be true since printable characters start as ASCII value 32
Change it to single quoted values
(date.charAt(0) == '0' && date.charAt(1) == '0')
|| (date.charAt(3) == '0' && date.charAt(4) == '0')
|| (date.charAt(0) == '3' && date.charAt(1) > '1')
|| (date.charAt(3) == '1' && date.charAt(4) > '2')
...
|| date.charAt(0) > '3'
|| date.charAt(3) > '1'
On an unreleated note, it's not a good idea to create the Exception object before checking for the condition. Exception creation can be expensive so don't waste the CPU time unless you need to throw it. This is better:
if(date.length() > 8 ...){
throw new IllegalDateFormatException("Date must have the following"
+ " format: dd/mm/yy");
}
this.date=date;

Using Simpledateformat may make your life a lot easier.
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yy");
try {
Date date = simpleDateFormat.parse("15/02/99");
} catch (ParseException e) {
throw IllegalDateFormat("Date must have the following format: " +
"dd/mm/yy");
}

charAt(someIndex)
returns a char not an int. You have to check for
== '0'

Related

I am trying to check if the phone number format is correct

The phone numbers that I will check have two formats:
(555) 555-5555 and 555-555-5555
However, my if condition keeps failing in the code below. I am trying to check if the str.charAt(0) is a ( or a number
public static boolean isPhoneNumber(String str) {
if (str.contains("-")) {
for (int i = 0; i < str.length(); i++) {
if ((i == 0 && str.charAt(0) != '(')
|| (i == 0 && Character.isDigit(str.charAt(0)) == false)) {
System.out.println(Character.isDigit(str.charAt(0)));
return false;
}
if (i == 4 && str.charAt(4) != ')' || i == 4 && !(Character.isDigit(str.charAt(4)))) {
System.out.println("here2");
return false;
}
if (i == 3 && str.charAt(3) != '-'
|| i == 3 && (Character.isDigit(str.charAt(3)) == false)) {
System.out.println(str.charAt(3));
return false;
}
if (i == 5 && str.charAt(5) != ' ' || i == 5 && !(Character.isDigit(str.charAt(5)))) {
System.out.println("here4");
return false;
}
if (i == 7 && str.charAt(i) != '-' || i == 7 && !(Character.isDigit(str.charAt(i)))) {
System.out.println("here5");
return false;
}
if (i == 9 && str.charAt(9) != '-' || i == 9 && !(Character.isDigit(str.charAt(9)))) {
System.out.println("here6");
return false;
}
if (i != 0 && i != 3 && i != 5 && i != 7 && i != 9 && !(Character.isDigit(str.charAt(i)))) {
System.out.println("here7");
return false;
}
}
return true;
} else {
return false;
}
}
A general regex pattern which might work here is:
^(?:\(\d{3}\)\s*|\d{3}-)\d{3}-\d{4}$
Here is an explanation of the above regex:
^ from the start of the input
(?:
\(\d{3}\) match (xxx)
\s* followed by optional whitespace
| OR
\d{3}- xxx-
)
\d{3}-\d{4} match xxx-xxxx
$ end of the input
Demo
This would cover both versions of the phone number you gave above. In Java, we can use String#matches here:
String phone1 = "(555) 555-5555";
String phone2 = "555-555-5555";
if (phone1.matches("(?:\\(\\d{3}\\)\\s*|\\d{3}-)\\d{3}-\\d{4}")) {
System.out.println(phone1 + " is in a valid format");
}
if (phone2.matches("(?:\\(\\d{3}\\)\\s*|\\d{3}-)\\d{3}-\\d{4}")) {
System.out.println(phone2 + " is in a valid format");
}

java. do not accept 0 as first input in a text field

I'm using Java and this part of my code is for entering age in a text field that only accepts numbers, back spaces and delete. How can I also tell the code to avoid accepting 0 if its the first character ?
Thank you.
Here is the code:
private void tfAgeKeyTyped(java.awt.event.KeyEvent evt) {
char c = evt.getKeyChar();
if(!(Character.isDigit(c)) || (c == KeyEvent.VK_BACK_SPACE) || (c == KeyEvent.VK_DELETE)){
evt.consume();
}
}
Well you just need to check if your entered character isn't equal to 0 in your condition using c == '0' when the current input is empty:
if((this.currentInput.isEmpty() && (!Character.isDigit(c) || c == '0')) || !(Character.isDigit(c)) || (c == KeyEvent.VK_BACK_SPACE) || (c == KeyEvent.VK_DELETE)){
evt.consume();
}
private void tfAgeKeyTyped(final java.awt.event.KeyEvent evt) {
final char c = evt.getKeyChar();
// You need access to the current input to known if you are on the
// first character or not.
// Here I assume it exists as a private member variable.
final boolean isFirstChar = this.currentInput.isEmpty();
final boolean isValidEvent = (Character.isDigit(c) && !(isFirstChar && c == '0')) ||
(c == KeyEvent.VK_BACK_SPACE) ||
(c == KeyEvent.VK_DELETE);
if (isValidEvent) {
evt.consume();
}
}

Reduce the number of conditional operators

How can I reduce the number of operators to 3 properly,
with multiple methods ? or loop ?
the constant of Actions is Int
String act = req.getParameter("ACTION");
int actInt = -1;
try {
actInt = Integer.parseInt(act);
} catch (NumberFormatException nfe) {
//
}
boolean actionNulle = act == null;
boolean actionDefaut = actionNulle || actInt == -1;
if ( (actionReq.equals(ACTION_LIST_ENREG) && (actionDefaut || !(actInt == Actions.AJOUTER || actInt == Actions.VALIDER || actInt == Actions.NOUVEAU || actInt == Actions.NOUVEAU_PAR_COPIE)))
|| (actionReq.equals("PreAbattage") && (actionDefaut || (actInt == Actions.DEFAUT)))
|| (actionReq.equals(ACTION_FORMULAIRE_RECHERCHE) && (actionDefaut || !(actInt == Actions.NOUVEAU_PAR_COPIE || actInt == Actions.NOUVEAU)))
|| (actionReq.equals("ModificationMultiple") && (actionDefaut || !(actInt == Actions.OUI || actInt == Actions.SUBSTITUTION)))
|| (actionReq.equals(ACTION_VISU_RECORD) && (actionDefaut || !(actInt == Actions.COPIE_PRIVE || actInt == Actions.NOUVEAU_PRIVE || actInt == Actions.MODIFIER || actInt == Actions.RESULTAT_CREATION)))
|| (actionReq.equals("VisuLock") && (actionDefaut || !(actInt == Actions.DETRUIRE_VERROU)))
|| (actionReq.equals("CopiePublique") && (actionDefaut || !(actInt == Actions.CREER_DONNEES_PUBLIQUES)))
|| (actionReq.equals("VisuSessions") && (actionDefaut || !(actInt == Actions.DETRUIRE_SESSION)))
|| (actionReq.equals(ACTION_VISU_MESSAGE) && (actionDefaut))
|| (actionReq.equals("RecapModifPub") && (actionDefaut || actInt == Actions.VALIDER))
) {
return true;
}
You could use a Map<String, Set<Integer>>
private final Map<String, Set<Integer>> validCombinations = initializeMap();
// initialize the map once
// later, in your code:
return validCombinations.containsKey(actionReq) &&
(actionDefault || validCombinations.get(actionReq).contains(actInt));

How to stop this java.lang.ArrayIndexOutOfBoundsException?

I'm trying validate my jtextfeild to enter only money value. which include only numeric and a full-stop. ex-17652.50
So I tried this method. But while it is executing I got this java.lang.ArrayIndexOutOfBoundsException: 1
Here is the method.
private void jTextField1KeyTyped(java.awt.event.KeyEvent evt) {
try {
char c = evt.getKeyChar();
String mny[] = jTextField1.getText().split("\\.");
if (!((c >= '0') && (c <= '9') || (c == KeyEvent.VK_BACK_SPACE) || (c == KeyEvent.VK_DELETE) || (c == KeyEvent.VK_ENTER) || (c == KeyEvent.VK_TAB) || (c == KeyEvent.VK_NUM_LOCK) || (c == '.'))) {
getToolkit().beep();
evt.consume();
}
if (mny[1].length() == 2) {
getToolkit().beep();
evt.consume();
}
} catch (Exception e) {
e.printStackTrace();
}
}
I am getting Array Index Out of Bounds Exception after I typed the first number in textfeild. As I understand this is happening because mny[o] should occur after I enter fullstop. But I can't find a solution. Please help me.
Thank you.
Iy there is no dot in you input String mny[] = jTextField1.getText().split("\\."); will return an array with only one item. Arrays in java are zero based. So mny[1].length() will throw an ArrayIndexOutOfBoundsException.
You should check here if your array have a size of 2
if (mny.length > 1 && mny[1].length() == 2) {
You could change your condition to :
if (mny.length > 1 && mny[1].length() == 2) {
getToolkit().beep();
evt.consume();
}
(or something similar, depending on the required logic)

Checking string for large amount of different, incremental values

Currently I am checking a string for the following:
if(parseCommand.contains("vlan1")
|| parseCommand.contains("Fa0/1i") || parseCommand.contains("Fa0/1o")
|| parseCommand.contains("Fa1/0") || parseCommand.contains("Fa1/1")
|| parseCommand.contains("Fa1/2") || parseCommand.contains("Fa1/3")
|| parseCommand.contains("Fa1/4") || parseCommand.contains("Fa1/5")
|| parseCommand.contains("Fa1/6") || parseCommand.contains("Fa1/7")
|| parseCommand.contains("Fa1/8") || parseCommand.contains("Fa1/9")
|| parseCommand.contains("Fa1/11") || parseCommand.contains("Gi0"))
{
//do things here
}
However it may contain vlan1 up to vlan4094 and i have to check for these. What is the simplest way to do this, do I have to stick it all in a for loop incrementing to 4094 I guess?
for (int i = 1; i <= 4094; i++)
{
if(parseCommand.contains("vlan"[i]))
{
//do stuff here
}
}
if(other conditions from above)
{
//do same stuff again here
}
Or else I could stick all the conditions in the for loop and do everything inside there. This all seems messy, is there a non-messy way of doing it?
I think this regex should do it:
String parseCommand = "vlan4094";
if (parseCommand.matches(".*?vlan([1-3][0-9]{3}|" +
"[1-9][0-9]{0,2}|" +
"40(9[0-4]|[0-8][0-9])).*"))
System.out.println("matches");
[1-3][0-9]{3} - 1000-3999
[1-9][0-9]{0,2} - 1-999
9[0-4] - 90-94
[0-8][0-9] - 00-89
40(9[0-4]|[0-8][0-9]) - 4000-4094
Something like this is probably simpler:
String parseCommand = "vlan4094";
if (parseCommand.startsWith("vlan"))
{
int v = Integer.parseInt(parseCommand.substring(4));
if (v >= 1 && v <= 4094)
/* do stuff */
}
Suggested change:
Replace:
parseCommand.contains("Fa1/0") || parseCommand.contains("Fa1/1")
|| parseCommand.contains("Fa1/2") || parseCommand.contains("Fa1/3")
|| parseCommand.contains("Fa1/4") || parseCommand.contains("Fa1/5")
|| parseCommand.contains("Fa1/6") || parseCommand.contains("Fa1/7")
|| parseCommand.contains("Fa1/8") || parseCommand.contains("Fa1/9")
with
parseCommand.matches(".*?Fa1/[0-9].*")
You can combie them into one boolean
boolean b = false;
for(int i = 1 ; i < 4094 ; i ++){
b = b || parseCommand.contains("vlan" + i);
}
Then check your boolean value
If the only problem is with "vlanXXX" you can remove the "vlan" part of the string:
parseCommand = parseCommand.replaceFirst("vlan", "");
and then cast it to int
int value = Integer.parseInt(parseCommand);
and then comparing this result with that whaat you want
if((value >= 1) && (value <= 4094)){....}
This will only work for the given case and you have to handle the case where parseCommand cannot be cast to int. And it is much more understandable than using whatever regular expresion

Categories

Resources