This question already has answers here:
What's the best way to check if a String represents an integer in Java?
(40 answers)
Closed 7 years ago.
I need to check whether the String is an Integer. And I found such solution:
private boolean isInteger(String str) {
try {
Integer.parseInt(str);
return true;
} catch (NumberFormatException e) {
return false;
}
}
Is there a more beautiful and proper way to do this without try/catch clause?
You can try a regex like:
Code
private boolean isInteger(String str) {
return str.matches("\\-?\\d+");
}
Edit
Thanks #Maloubobola for noting that my first attempt would not parse signed integers.
You can try regex. Here is one for positive and negative numbers
private boolean isInt(String string) {
return string.matches("-?\\d+");
}
Related
This question already has answers here:
How to find a whole word in a String in Java?
(14 answers)
Closed 2 years ago.
I´m doing a project for school and I need my method to return true only to a certain word.
This is what I have:
public boolean scanDescription (String keyword) {
if (description.contains(keyword)) {
return true;
} else {
return false;
}
So for example, if the keyword is "disk", I need this method to return true only when a string contains the word "disk", but my problem is that it returns true when a string contains words like "diskette"
PS.: I have also tried to use .indexOf and it did not work
You should use the word boundary.
public boolean scanDescription(String keyword) {
Pattern pattern = Pattern.compile("\\b"+keyword+"\\b");
return pattern.matcher(description).find();
}
This question already has answers here:
Try-catch-finally-return clarification [duplicate]
(2 answers)
Multiple returns: Which one sets the final return value?
(7 answers)
Closed 5 years ago.
Hi I have a question about catch and finally.
I looked around for the same case but had no luck but I'm sure this has been asked before.. so this may be a duplicate. Sorry for that.
Anyway this is my question:
Here is a method which returns a boolean
public static boolean runtimeException() {
try {
int i = 1 / 0;
} catch (ArithmeticException ae) {
return true;
} finally {
return false;
}
}
When I call this method in my main function:
public static void main(String[] args) {
boolean flag = runtimeException();
System.out.println(flag);
}
The result is: "false".
Id like to know why this happens.
I know that the finally block has to be executed at any means but logically the results don't make sense to me because the catch block is executed before and the function has already returned true. How can the function return false after already returning true??
Thanks in advance.
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 6 years ago.
public static boolean stringToBoolean (String horv) {
if (horv == "H") {
return true;
} if (horv == "V") {
return false;
} else {
return true;
}
This is a small part of a program I am creating. The program is reading from a file and inputting the data into an array. For this part it is reading what will either be a "H" or "V" from the file and converting it to a boolean value. The problem is when I run the program I am only getting true for every value, even the ones that have a "V" as their variable.
Change the code to be:
if ("H".equals(horv)) { return true; }
...
Try This
public static boolean stringToBoolean (String horv) {
if ("H".equals(horv)) { // use equals method for string comparison
return true;
} if ("V".equals(horv)) {
return false;
} else {
return true;
}
String variables should be compared with equals() method in java.
In Java you have compare String with a method equals() Like this
public static boolean stringToBoolean (String horv) {
if (horv.equals("H")) return true;
if (horv.equals("V")) return false;
return true;
}
This question already has answers here:
Best implementation for an isNumber(string) method
(19 answers)
Closed 7 years ago.
I have a lot of code that gathers user input and parses it,
I want to parse integer values without throwing exceptions.
My current tryParseInt() function is code is simple:
public static Integer tryParseInt( String text )
{
if(text == null)
return null;
try
{
return new Integer( text.trim() );
}
catch ( NumberFormatException e )
{
return null;
}
}
But i am getting lots of NumberFormatExceptions and i am worried becouse that may impact my app performance.
Can anyone suggest me on best practice for parsing user inputs.
Thank you
You can go with regex as it is more fail proof
public static Integer tryParseInt(String text) {
if (text != null && !text.isEmpty()) {
if (text.trim().matches("[0-9]+")) {
return Integer.valueOf(text.trim());
}
}
return null;
}
This is a very helpful experiment and indeed my experience is removing exceptions is better for performance
If you are getting a lot of NumberFormatExceptions, you might consider checking the parsing input before the actual parsing.
BTW the return new Integer( text.trim() ); is not very efficient as you will be allocating a lot of unnecessary objects (in the range from -128 to 127).
public static Integer tryParseInt(String text) {
if(text == null)
return null;
try {
return Integer.valueOf(text.trim());
}
catch (NumberFormatException e) {
return null;
}
}
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I'm writing some codes that test if there is "xx" in a string. For instance, doubleX("aaxxbb") should return true, and doubleX("axabb") should return false.
Here is my code:
private static boolean doubleX(String str) {
for(int i=0;i<str.length()-1;i++){
System.out.println(str.substring(i,i+2));
if(str.substring(i,i+2) == "xx") return true;
}
return false;
}
Why does doubleX("aaxxbb") return false?
You have to use .equals instead of ==. For more information, follow the duplication message.
return str.contains("xx");
Is a lot clearer though.
You should understand the difference between == and equals: the first one compares references, the second compares actual values.
Your code is wildly inefficient.
I'd try something like this:
private static boolean doubleX(String str) {
return (str.indexOf("xx") != -1);
}
Use equals() for checking the content of a String to another rather than ==. == checks for reference equality.
private static boolean doubleX(String str) {
for(int i=0;i<str.length()-1;i++){
System.out.println(str.substring(i,i+2));
if(str.substring(i,i+2).equals("xx")) return true;
}
return false;
}
Even you can directly code like:
private static boolean doubleX(String str) {
return str.contains("xx");
}