1

I enter a list into a JTextArea, and when I push a button, it runs the method below. I need to check to see if str[i+1], str[i+2] is a String and not an int.

public void readData(JTextArea input) {
    String[] str = input.getText().split("\n");
    for(int i =1; i< str.length; i= i+3) {
        try {
            Integer.parseInt(str[i]);
            simulator.add(new Process(Integer.parseInt(str[i]), str[i+1],str[i+2])); 
        } catch(NumberFormatException e) {
            System.out.println("Please enter an integer only " +
                                str[i] + " is not an integer");
        }
    }
}
1
  • It is of course a string, since you are getting the text from a JTextArea. Commented Sep 10, 2014 at 3:04

5 Answers 5

3

You could have a function that tries to parse the string into an Integer or a Double and return true if it succeeded, or return false is an exception was thrown during parsing. Parsing into a Double should be enough since all integer values are decimal values without the .0

public static boolean isNumber(String s) {
    try {  
        Double.parseDouble(s);
        /* Use Integer.parseInt(s) instead, if
           you want to check if the String s
           is an Integer */
    } catch(NumberFormatException e) { // string is not a number
        return false; 
    }
    return true;
}

Then you can say if(!isNumber(str)) to check if the String str is not a number.

Alternatively, you could make the isNumber() be a isNotNumber() by swapping the return false and return true statements.

If you don't want to use exceptions, a different approach would be the following. Since we know a valid number can only contain digits and at most 1 dot for decimal point, we can iterate through the string and check for each character:

  • if it is not a digit and not a dot, return false
  • if it is a dot but a dot was already found, return false
  • otherwise it is valid number character and we do nothing

Here is a sample function:

public static boolean isNumber(String s) {
    int dotCount = 0;
    for(int i = 0; i < s.length(); i++) {
        if(s.charAt(i) != '.' && !Character.isDigit(s.charAt(i))) {
            return false;
        } else if(s.charAt(i) == '.') {
            if(dotCount == 1) {
                return false;
            }
            dotCount = 1;
        }
    }
    return true;
}

EDIT: based on @MadProgrammer's suggestions:

A more general approach that will accept values separated with commas such as 1,35 or any amount of spaces within the number string like with 123 456 . 333.

Approach:

Iterate through the string and check for each character:

  • if it is not a digit, dot, comma, or a space, return false
  • if it is a dot or a comma but one of them was already found, return false
  • otherwise it is valid number character and we do nothing

So the code would look something like:

public static boolean isNumber(String s) {
    int separatorCount = 0; // count dots and commas
    char currChar;
    s.trim();  // remove trailing and leading whitespace
    for (int i = 0; i < s.length(); i++) {
        currChar = s.charAt(i);
        if (currChar != '.' && currChar != ',' && currChar != ' '
                && !Character.isDigit(currChar)) {
            return false;
        } else if (currChar == '.' || currChar == ',') {
            if (separatorCount == 1) {
                return false;
            }
            separatorCount = 1;
        }
    }
    return true;
}

Another solution could use the NumberFormat's parse() method. However, this method only checks the beginning of the string (for example, for 12.3.3 it will return 12.3) so we have to return false if the returned string doesn't equal the input string as well as if the ParseException is thrown.

public static boolean isNumber(String s) {
    try {
        String newVal = NumberFormat.getInstance().parse(s).toString();
        if (!newVal.equals(s)) {
            return false;
        }
    } catch (ParseException e) {
        return false;
    }
    return true;
}

NOTE: All of the methods should probably have a check if(s == null) { return false; } for the input String s to prevent a NullPointerException

Sign up to request clarification or add additional context in comments.

7 Comments

You could try using a NumberFormat instead of using the isNumber value...as an idea ;)
@MadProgrammer I assume this wouldn't work for every value. In the docs for NumberFormat.getInstance().parse() it says: Parses text from the beginning of the given string to produce a number. The method may not use the entire text of the given string. and if I parse 12.3.3 it doesn't cause an exception. Is this what you meant?
Yeah, it was just an off the head idea, haven't tested it myself, but it might save some work ;) - Mind you, a DocumentFilter on the text field itself, could solve all these problems ;)
Having tested it (now), 12.3.3 returns 12.3, in those case you could check to see if the two values, when converted to String are the same...
@MadProgrammer thanks for the suggestions, will test/add 'em now.
|
2

Your rules are sparse, you don't specify if things like , or . are considered part of a number or not (1, 000.01 for example), also, you don't define if the value is allowed to contain numerical values or not, but...

You Could...

Try parsing each value (or the concatenation of the two) using Integer.parseInt, if they pass, then they are not String (or text) based values...

You Could...

Verify each character within the String to see if it contains more than just digits, using something like Character#isLetter

You Could...

Use a regular expression to determine if the value contain other content other than numbers.

Comments

2

You can try this simple regular expression to check if a string represents a number or not:-

String str = "12345";
System.out.println(str.matches("\\d+"));

Comments

0

Regex seems the best option. Here's a regex that will parse float and integers and currency values with comma as well.

 String numberRex = "^([\\d]*\\.*\\d*|[\\d,]*\\.*\\d*)$";
 "1234,455.43".matches(numberRex); // true

Comments

0

This is a simple test that asserts there is at least one non numeric char:

if (str.matches(".*[^\\d.].*"))

the regex translates as "somewhere in the input there's a character that's not a digit or a dot"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.