I was trying to write a piece of code to test if a string contains an integer. I am aware of the try catch solution, but i have read it becomes bad if you call the method from other classes. What I have read is that the method will show the error, but the main of the class calling it will keep running anyway.
Therefore, I was trying to do it manually. My problem is that i am able to assess that the string is not empty and that all the characters in the string are digits, but I can't find a way to verify whether the number is too big to be sorted in an integer. Point is, i have found on stackoverflow many similar topics, but noone solve this problem without try catch.
Here is my method.
// INTEGER VERIFICATION
public static boolean isInteger (String str_input){
int number_of_digits = 0;
if (str_input.isEmpty()) {
JOptionPane.showMessageDialog(null, "No input inserted", "Error", JOptionPane.ERROR_MESSAGE);
return false;
}
for (char c : str_input.toCharArray()){
if(Character.isDigit(c)){
number_of_digits++;
}
}
if (number_of_digits == str_input.length()){
return true;
}
else {
JOptionPane.showMessageDialog(null, "The input is not an integer", "Error", JOptionPane.ERROR_MESSAGE);
return false;
}
}
Thanks in advance for your help!
I think the best way to do this is as pointed by Leo in the comments.
public static boolean isInteger(final String strInput) {
boolean ret = true;
try {
Integer.parseInt(strInput);
} catch (final NumberFormatException e) {
ret = false;
}
return ret;
}
Also I suggest you separate the GUI part from the checking method, let the caller decide what to do if false (for example, maybe in some situations you want to check if it's an integer but don't show the dialog).
You could modify your method to make sure the number fits within an int.
It can be done by parsing the input as long, and checking against the range of int numbers.
// INTEGER VERIFICATION
public static boolean isInteger (String str_input){
int number_of_digits = 0;
if (str_input.isEmpty()) {
JOptionPane.showMessageDialog(null, "No input inserted", "Error", JOptionPane.ERROR_MESSAGE);
return false;
}
for (char c : str_input.toCharArray()){
if(Character.isDigit(c)){
number_of_digits++;
}
}
if (number_of_digits == str_input.length()){
if (str_input.length > 15) // arbitrary length that is too long for int, but not too long for long
return false;
long number = Long.parseLong(str_input);
if (number > Integer.MAX_VALUE || number < Integer.MIN_VALUE)
return false;
else
return true;
}
else {
JOptionPane.showMessageDialog(null, "The input is not an integer", "Error", JOptionPane.ERROR_MESSAGE);
return false;
}
}
BTW, if you allow negative inputs, you should change your check to allow '-' as the first character.
That said, I agree with all the comments that say you'd be better off to just call Integer.parseInt() and catch the exception.
How about using Regex
-?\\d+(\\.\\d+)? which accept negative and decimal numbers
Source: http://www.vogella.com/tutorials/JavaRegularExpressions/article.html
public static boolean isNumeric(String str) {
return str.matches("-?\\d+(\\.\\d+)?");
}
Related
I ask the user to input a number until the user finds it.
I'm having trouble validating every input whether the user is typing in a number or anything else like char or string.
So basically I'm trying to prevent any mismatch exception error.
If you're writing code to take input as an integer, then it should come as an error or not move on if it doesn't have an int as an input.
If you're writing code to take a char or a string as an integer, then you should use Integer.parseInt() to convert your input to an int value.
Try to parse the text as a number, and if it fails, catch the failure and prompt the user to reenter the number.
Should be enough of a hint to get you going.
You can try to parse the String as a double and catch a NumberFormatException which will indicate that the input is not a valid number.
private static boolean isNumber(String s){
try{
Double.parseDouble(s);
return true;
} catch (NumberFormatException e){
return false;
}
}
If you want to not allow the String "NaN" to be accepted as a number, you can check if the String is equal to "NaN" before parsing it.
private static boolean isNumber(String s){
if(s.trim().equals("NaN")){
return false;
}
try{
Double.parseDouble(s);
return true;
} catch (NumberFormatException e){
return false;
}
}
I've been assigned the simple task of:
1) Accepting a Scanner argument and reading space-separated words from it.
2) If a word is a valid real number such as 0.1 or -3.14159 or 87 then add the number onto a running total.
3) When there is no more input available in the scanner, return total.
This is the magic that I have produced so far:
public static double sumReal(Scanner input) {
while(input.hasNext()) {
}
}
I understand that "hasNext" returns a boolean, but how can I confirm that it is a double and not a string?
Any help greatly appreciated!
Maybe the hasNextDouble() - Method will do the trick.
//some code
while (input.hasNextDouble()) {
//do something
}
Use
while (isDouble(input.nextLine())) {
// your code
}
& add a method to check if a number is Double or not
public static boolean isDouble(String str) {
try {
Double.parseDouble(str);
return true;
} catch (NumberFormatException e) {
return false;
}
}
I have this validation to check that user input is not blank and is only letters. If it's blank, it catches it, and if if includes digits it also catches it. If I input the 2 characters it asks for, however, it doesn't go through. I'm not sure how to go about this.
private static boolean isValidSt(String aSt) {
boolean result = false;
try {
if (aSt.length() == 2) {
result = true;
} else if (aSt.length() != 2) {
result = false;
}
for (int i=0; i <aSt.length();){
if (!Character.isLetter(i));{
return false;
}
}
return true;
} catch (NumberFormatException nfex) {
if (aSt == null) System.exit(0);
} catch (Exception ex) {
if (aSt == null) System.exit(0);
}
return result;
}
One problem that I can see right of the bat is this:
if (!Character.isLetter(i));{
return false;
}
That semi-colon after your if does not belong there. After checking your conditional statement, if it was true, it will execute until the semi-colon. The return false; isn't part of the if and will ALWAYS be executed.
As David Wallice rightly pointed out, you also never increment the counter in your for-loop, so were it not the case that the program always returned with false in the first iteration, it would indeed get stuck in an eternal loop. A very commonly used syntax for for-loops would be:
for(int i = 0; i < string.length(); i++) { }
A third and final note from me, this time nothin that would give an error, just good form:
You use System.exit(0); to exit the program as result of an exception. The zero you pass as an argument is usually only used when the program shuts down normally. This is a crash as a result of an error, so I'd use 1 or something.
Well, you could use StringUtils methods, isBlank and isAlpha, for validate what you need
So I need to create a method isValidDNA which works like this:
public boolean isValidDNA()
Returns true if the DNA is valid, i.e, only contains the letters,
A,T,C,G (in uppercase) and at least one of these characters.
All I could think of was this, which apparently doesn't work:
public boolean isValidDNA(){
for (int i=0;i<dna.length();i++){
if (dna.charAt(i)=='A' || dna.charAt(i)=='T' || dna.charAt(i)=='C' || dna.charAt(i)=='G' ){
return true;
}
return false;
}
}
You can use this regular expression:- [ATCG]+ In code this could look like this:
public boolean isValidDNA(){
return dna.matches("^[ATCG]+$")
}
You make a return statement immediately, which will exit during the first iteration and only check the first character.
You need to store this information in a boolean and return it after you've checked the whole string:
public boolean isValidDNA(String dna){
Boolean result = true;
// Add an extra check for the "at least one character" thing.
for (int i=0; i<dna.length(); i++){
if (dna.charAt(i)!='A' && dna.charAt(i)!='T' && dna.charAt(i)!='C' && dna.charAt(i)!='G' ){
result = false;
}
}
return result;
}
However, you would be better off using regular expressions for these problems.
Try it this way:
public boolean isValidDNA(){
boolean res = true;
for (int i=0;i<dna.length();i++){
if ((dna.charAt(i) != 'A') && (dna.charAt(i)!='T') && (dna.charAt(i)!='C') && (dna.charAt(i)!='G') ){
res = false;
break;
}
}
return res;
}
if your startpoint is that the DNA is valid, it's much more easy to test if it's really so. You only have to test each char of your dna and can stop by the first entry that doesn't satisfy your if-statement.
Using your way, you've almost got it.
Right now, you return true if you find one that's OK, and only return false if all are wrong. You can negate your if condition, and return false as soon as you find one that's not OK, and only return true if all are fine.
I'll leave the coding part up to you.
As others pointed out, regex will be a cleaner solution here.
You can try this implementation.
First declare a constant:
private static final String bases = "ATCG";
And then use it in the method like this:
public boolean isValidDNA() {
boolean isValid = true;
for (char c : dna.toCharArray()) {
if (bases.indexOf(c) < 0) {
isValid = false;
break;
}
}
return isValid;
}
Scanner sc = new Scanner(System.in);
System.out.print("Enter a DNA sequence: ");
seq=sc.nextLine();
if(seq.matches(".*[^ATCG].*")){
System.out.println("Not a valid sequence.");
System.exit(0);
}
This regular expression works so that only sequences containg A,C,T or G with no other charcters, spaces, etc included will continue
This question already has answers here:
What's the best way to check if a String represents an integer in Java?
(40 answers)
Closed 9 years ago.
I'm trying to determine if a particular item in an Array of strings is an integer or not.
I am .split(" ")'ing an infix expression in String form, and then trying to split the resultant array into two arrays; one for integers, one for operators, whilst discarding parentheses, and other miscellaneous items. What would be the best way to accomplish this?
I thought I might be able to find a Integer.isInteger(String arg) method or something, but no such luck.
The most naive way would be to iterate over the String and make sure all the elements are valid digits for the given radix. This is about as efficient as it could possibly get, since you must look at each element at least once. I suppose we could micro-optimize it based on the radix, but for all intents and purposes this is as good as you can expect to get.
public static boolean isInteger(String s) {
return isInteger(s,10);
}
public static boolean isInteger(String s, int radix) {
if(s.isEmpty()) return false;
for(int i = 0; i < s.length(); i++) {
if(i == 0 && s.charAt(i) == '-') {
if(s.length() == 1) return false;
else continue;
}
if(Character.digit(s.charAt(i),radix) < 0) return false;
}
return true;
}
Alternatively, you can rely on the Java library to have this. It's not exception based, and will catch just about every error condition you can think of. It will be a little more expensive (you have to create a Scanner object, which in a critically-tight loop you don't want to do. But it generally shouldn't be too much more expensive, so for day-to-day operations it should be pretty reliable.
public static boolean isInteger(String s, int radix) {
Scanner sc = new Scanner(s.trim());
if(!sc.hasNextInt(radix)) return false;
// we know it starts with a valid int, now make sure
// there's nothing left!
sc.nextInt(radix);
return !sc.hasNext();
}
If best practices don't matter to you, or you want to troll the guy who does your code reviews, try this on for size:
public static boolean isInteger(String s) {
try {
Integer.parseInt(s);
} catch(NumberFormatException e) {
return false;
} catch(NullPointerException e) {
return false;
}
// only got here if we didn't return false
return true;
}
It's better to use regular expression like this:
str.matches("-?\\d+");
-? --> negative sign, could have none or one
\\d+ --> one or more digits
It is not good to use NumberFormatException here if you can use if-statement instead.
If you don't want leading zero's, you can just use the regular expression as follow:
str.matches("-?(0|[1-9]\\d*)");
Or you can enlist a little help from our good friends at Apache Commons : StringUtils.isNumeric(String str)
You want to use the Integer.parseInt(String) method.
try{
int num = Integer.parseInt(str);
// is an integer!
} catch (NumberFormatException e) {
// not an integer!
}
Or simply
mystring.matches("\\d+")
though it would return true for numbers larger than an int
As an alternative approach to trying to parse the string and catching NumberFormatException, you could use a regex; e.g.
if (Pattern.compile("-?[0-9]+").matches(str)) {
// its an integer
}
This is likely to be faster, especially if you precompile and reuse the regex.
However, the problem with this approach is that Integer.parseInt(str) will also fail if str represents a number that is outside range of legal int values. While it is possible to craft a regex that only matches integers in the range Integer.MIN_INT to Integer.MAX_INT, it is not a pretty sight. (And I am not going to try it ...)
On the other hand ... it may be acceptable to treat "not an integer" and "integer too large" separately for validation purposes.
You can use Integer.parseInt(str) and catch the NumberFormatException if the string is not a valid integer, in the following fashion (as pointed out by all answers):
static boolean isInt(String s)
{
try
{ int i = Integer.parseInt(s); return true; }
catch(NumberFormatException er)
{ return false; }
}
However, note here that if the evaluated integer overflows, the same exception will be thrown. Your purpose was to find out whether or not, it was a valid integer. So its safer to make your own method to check for validity:
static boolean isInt(String s) // assuming integer is in decimal number system
{
for(int a=0;a<s.length();a++)
{
if(a==0 && s.charAt(a) == '-') continue;
if( !Character.isDigit(s.charAt(a)) ) return false;
}
return true;
}
You can use Integer.parseInt() or Integer.valueOf() to get the integer from the string, and catch the exception if it is not a parsable int. You want to be sure to catch the NumberFormatException it can throw.
It may be helpful to note that valueOf() will return an Integer object, not the primitive int.
public boolean isInt(String str){
return (str.lastIndexOf("-") == 0 && !str.equals("-0")) ? str.substring(1).matches(
"\\d+") : str.matches("\\d+");
}