How to stop this java.lang.ArrayIndexOutOfBoundsException? - java

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)

Related

Of the two constructers one works and the other doesn't when the argument is correct

i'm new to programming. i don't understand why one of the constructers I'm using to check for the validity of the characters of a string argument in the constructer does not work. the constructer should check if the entered string contains only characters G,C,A,T, else it throws an IllegalArgumentException.
I tried using an array of characters to check for the validity of the string by using the toCharArray() method on the entered string. the constructer works for invalid strings, but not for valid strings. but another constructer i used works. please let me know why the first one doesn't.
//this is the first constructer that doesn't work for me
public class Fragment {
private String nucleotideSequence;
public Fragment(String nucleotides) throws IllegalArgumentException {
char[] validityCheck = nucleotides.toCharArray();
int validityCounter = 0;
for (char c : validityCheck) {
if(c != 'G' || c != 'C' || c != 'A' || c != 'T') {
validityCounter++;
}
}
if (validityCounter != 0) {
throw new IllegalArgumentException("Invalid characters present");
}
nucleotideSequence = nucleotides;
}
}
// this is the second constructer that works
public class Fragment {
private String nucleotideSequence;
public Fragment(String nucleotides) throws IllegalArgumentException {
boolean k = false;
for(int i = 0; i < nucleotides.length(); i++){
char lol = nucleotides.charAt(i);
if(lol=='A'||lol=='G'||lol=='C'||lol=='T'){
k = true;
}
else{
k = false;
}
if(k == false){
throw new IllegalArgumentException("Dosent work");
}
nucleotideSequence = nucleotides;
}
}
}
Your problem in the constructor that is not working is with the following 'if' statement:
if(c != 'G' || c != 'C' || c != 'A' || c != 'T')
This statement is always true. So the following:
for (char c : validityCheck) {
if(c != 'G' || c != 'C' || c != 'A' || c != 'T') {
validityCounter++;
}
}
equals:
for (char c : validityCheck) {
validityCounter++;
}
the correct statement would be
if(c != 'G' && c != 'C' && c != 'A' && c != 'T') {

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();
}
}

Where I am wrong? (Exception handling)

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'

Cannot find symbol, Java and Strings

I've tried tinkering around with this for awhile and have yet to figure out what its giving me this error. The code is far from complete but I'm just trying to figure out why it says it can't find variable ch1. Any help is greatly appreciated!
public class PhoneNumber {
String phoneNumber;
public PhoneNumber(String num) {
phoneNumber = num;
}
public String decodePhoneNumber() {
// Takes string form phone number and decodes based on number pad
// Find code that makes if statement not care about caps
// so if a || b || c number[cnt] = 1 etc..
for (int cnt = 0; cnt < phoneNumber.length(); cnt++) {
char ch1 = phoneNumber.charAt(cnt);
if (Character.ch1.equalsIgnoreCase("a") || ("b") || ("c")) {
} else if (ch1.equalsIgnoreCase("d" || "e" || "f")) {
} else if (ch1.equalsIgnoreCase("j" || "k" || "l")) {
} else if (ch1.equalsIgnoreCase("m" || "n" || "o")) {
} else if (ch1.equalsIgnoreCase("p" || "q" || "r" || "s")) {
} else if (ch1.equalsIgnoreCase("t" || "u" || "v")) {
} else {
}
}
}
}
You have syntax errors and that is why you cannot find ch1.
Try modifying your code as per this syntax. These changes need to be done in all the conditionals.
if ((ch1 == 'a') || (ch1 == 'b') || (ch1 =='c')) {
If you want to make it work regardless of capital letters then you would need to normalize the input to lower case and then do the character comparison:
char ch1 = phoneNumber.toLowerCase().charAt(cnt);
if (ch1 == 'a' || ch1 == 'b' || ch1 == 'c') {
// Do something
}
...

Java Input Numbers

I made ​​a method to input numbers. But I want that input is numeric but a dot (.) Can still be entered. please my friend help me. Thanks
private void jTextField1KeyTyped(java.awt.event.KeyEvent evt) {
// TODO add your handling code here:
FilterHanyaAngka(evt);
}
public void FilterHanyaAngka(java.awt.event.KeyEvent evt) {
char c = evt.getKeyChar();
if (!((Character.isDigit(c) || (c == KeyEvent.VK_BACK_SPACE) || (c == KeyEvent.VK_DELETE)))) {
evt.consume();
}
}
Don't use KeyListener to filter content to the a text component, you have no idea of knowing in what order the KeyListeners will be notified and the key stroke may already have being sent to the field before you.
Instead you should use a DocumentFilter
Take a look at Text Component Features, in particular Implementing a Document Filter and here for examples
In fact, I believe there is actually a numeric filter example listed there...
You can use ASCII instead of the Character or KeyEvent class.
Look at this:
public class ASCIITest {
public static void main(String[] args) {
char c = '3';
if ((c >= '0' && c <= '9') || c == '.') {
//some code..
}
}
}
For more information read about the ASCII chart
yes I've found the solution in my opinion
public void filterDesimal(java.awt.event.KeyEvent evt) {
char ch = evt.getKeyChar();
if (!((ch == '.') ||
(ch == '0') ||
(ch == '1') ||
(ch == '2') ||
(ch == '3') ||
(ch == '4') ||
(ch == '5')||
(ch == '6') ||
(ch == '7') ||
(ch == '8') ||
(ch == '9') ||
(ch == ',') ||
(ch == KeyEvent.VK_BACK_SPACE) ||
(ch == KeyEvent.VK_DELETE)
)){
evt.consume();
}
}

Categories

Resources