This question already has answers here:
How to check if a String is numeric in Java
(41 answers)
Closed 6 years ago.
I have a gpa program, and it works with the equalsIgnoreCase() method which compares two strings, the letter "a" to the user input, which checks if they put "a" or not. But now I want to add an exception with an error message that executes when a number is the input. I want the program to realize that the integer input is not the same as string and give an error message. Which methods can I use to compare a type String variable to input of type int, and throw exception?
Many options explored at http://www.coderanch.com/t/405258/java/java/String-IsNumeric
One more is
public boolean isNumeric(String s) {
return s != null && s.matches("[-+]?\\d*\\.?\\d+");
}
Might be overkill but Apache Commons NumberUtils seems to have some helpers as well.
If you are allowed to use third party libraries, suggest the following.
https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/math/NumberUtils.html
NumberUtils.isDigits(str:String):boolean
NumberUtils.isNumber(str:String):boolean
Use this
public static boolean isNum(String strNum) {
boolean ret = true;
try {
Double.parseDouble(strNum);
}catch (NumberFormatException e) {
ret = false;
}
return ret;
}
You can also use ApacheCommons StringUtils.isNumeric - http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringUtils.html#isNumeric(java.lang.String)
Simple method:
public boolean isBlank(String value) {
return (value == null || value.equals("") || value.equals("null") || value.trim().equals(""));
}
public boolean isOnlyNumber(String value) {
boolean ret = false;
if (!isBlank(value)) {
ret = value.matches("^[0-9]+$");
}
return ret;
}
Use below method,
public static boolean isNumeric(String str)
{
try
{
double d = Double.parseDouble(str);
}
catch(NumberFormatException nfe)
{
return false;
}
return true;
}
If you want to use regular expression you can use as below,
public static boolean isNumeric(String str)
{
return str.matches("-?\\d+(\\.\\d+)?"); //match a number with optional '-' and decimal.
}
public static boolean isNumeric(String string) {
if (string == null || string.isEmpty()) {
return false;
}
int i = 0;
int stringLength = string.length();
if (string.charAt(0) == '-') {
if (stringLength > 1) {
i++;
} else {
return false;
}
}
if (!Character.isDigit(string.charAt(i))
|| !Character.isDigit(string.charAt(stringLength - 1))) {
return false;
}
i++;
stringLength--;
if (i >= stringLength) {
return true;
}
for (; i < stringLength; i++) {
if (!Character.isDigit(string.charAt(i))
&& string.charAt(i) != '.') {
return false;
}
}
return true;
}
I wrote this little method lastly in my program so I can check if a string is numeric or at least every single char is a number.
private boolean isNumber(String text){
if(text != null || !text.equals("")) {
char[] characters = text.toCharArray();
for (int i = 0; i < text.length(); i++) {
if (characters[i] < 48 || characters[i] > 57)
return false;
}
}
return true;
}
You can use Character.isDigit(char ch) method or you can also use regular expression.
Below is the snippet:
public class CheckDigit {
private static Scanner input;
public static void main(String[] args) {
System.out.print("Enter a String:");
input = new Scanner(System.in);
String str = input.nextLine();
if (CheckString(str)) {
System.out.println(str + " is numeric");
} else {
System.out.println(str +" is not numeric");
}
}
public static boolean CheckString(String str) {
for (char c : str.toCharArray()) {
if (!Character.isDigit(c))
return false;
}
return true;
}
}
Here's how to check if the input contains a digit:
if (input.matches(".*\\d.*")) {
// there's a digit somewhere in the input string
}
To check for all int chars, you can simply use a double negative.
if (!searchString.matches("[^0-9]+$")) ...
[^0-9]+$ checks to see if there are any characters that are not integer, so the test fails if it's true. Just NOT that and you get true on success.
Related
I am in school for Java and the current assignment I have is slowly building a calculator. the teacher uploaded the wrong lectures on the current part and I can't find a solution to my problem. so I have my main method where input is handled and the input is passed to two functions. one validates that real numbers were entered, and the second function validates that the numbers are separated by a valid operator (^ * / + -). I figured out the number validation but I don't know how to validate the operator in the string. The input string must be validated before the main function changes the input in to an array and continues. here is my code so far
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
ArrayList<String> validOperators = new ArrayList<String>(){{
add("^");
add("*");
add("/");
add("+");
add("-");
}};
System.out.println("This is a text based calculator!");
Scanner in = new Scanner(System.in);
boolean loop = true;
while (loop) {
System.out.println("Enter a math expression ot type quit to exit: ");
String math = in.nextLine();
if ("quit".equalsIgnoreCase(math)) {
System.out.print("Quitting");
break;
}
if (isOperator(math)){
String[] splitExpression = math.split("\\s+");
if (isNumber(splitExpression)){
for (int i=0; i<splitExpression.length; i++){
System.out.println(splitExpression[i]);
}
System.out.println("Number of tokens: " + splitExpression.length);
}else {
System.out.println("invalid expression!");
}
}else{
System.out.println("please use valid operators");
}
}
}
public static boolean isNumber(String[] number){
try {
double test = Double.parseDouble(number[0]);
double test2 = Double.parseDouble(number[2]);
} catch (Exception e){
return false;
}
return true;
}
public static boolean isOperator(String operator){
if (operator.contains("^")){
return true;
}else{
return false;
}
}
public static boolean isValidExpression(String[] strArray){
String strOfArray = Arrays.toString(strArray);
return;
}
}
isOperator() is checking for exponential operator, you may need to check for addition(+), substration(-), multiplication(*) ,division(/) and modulo(%)
isOperator
public static boolean isAnOperator(char c) {
switch (c) {
case '*':
case '/':
case '+':
case '-':
case '%':
return true;
default:
return false;
}
}
update isANumber to check if given charater of string is a number
public static boolean isANumber(char c){
return ((int)c) >= 48 && ((int)c) <= 57;
}
isValidExpression()
public static boolean isValidExpression(String expression) {
if (isAnOperator(expression.charAt(0)) || isAnOperator(expression.charAt(expression.length() - 1))) {
return false;
}
int openParenthCount = 0;
boolean lastWasOp = false;
boolean lastWasOpen = false;
for (char c : expression.toCharArray()) {
if(c == ' ') continue;
if (c == '(') {
openParenthCount++;
lastWasOpen = true;
continue;
} else if (c == ')') {
if (openParenthCount <= 0 || lastWasOp) {
return false;
}
openParenthCount--;
}else if (isAnOperator(c)){
if (lastWasOp || lastWasOpen) return false;
lastWasOp = true;
continue;
}else if(!isANumber(c)){
return false;
}
lastWasOp = false;
lastWasOpen = false;
}
if(openParenthCount != 0) return false;
if(lastWasOp || lastWasOpen) return false;
return true;
}
I'm trying to verify if a String s match/is a real number. For that I created this method:
public static boolean Real(String s, int i) {
boolean resp = false;
//
if ( i == s.length() ) {
resp = true;
} else if ( s.charAt(i) >= '0' && s.charAt(i) <= '9' ) {
resp = Real(s, i + 1);
} else {
resp = false;
}
return resp;
}
public static boolean isReal(String s) {
return Real(s, 0);
}
But obviously it works only for round numbers. Can anybody give me a tip on how to do this?
P.S: I can only use s.charAt(int) e length() Java functions.
You could try doing something like this. Added recursive solution as well.
public static void main(String[] args) {
System.out.println(isReal("123.12"));
}
public static boolean isReal(String string) {
boolean delimiterMatched = false;
char delimiter = '.';
for (int i = 0; i < string.length(); i++) {
char c = string.charAt(i);
if (!(c >= '0' && c <= '9' || c == delimiter)) {
// contains not number
return false;
}
if (c == delimiter) {
// delimiter matched twice
if (delimiterMatched) {
return false;
}
delimiterMatched = true;
}
}
// if matched delimiter once return true
return delimiterMatched;
}
Recursive solution
public static boolean isRealRecursive(String string) {
return isRealRecursive(string, 0, false);
}
private static boolean isRealRecursive(String string, int position, boolean delimiterMatched) {
char delimiter = '.';
if (position == string.length()) {
return delimiterMatched;
}
char c = string.charAt(position);
if (!(c >= '0' && c <= '9' || c == delimiter)) {
// contains not number
return false;
}
if (c == delimiter) {
// delimiter matched twice
if (delimiterMatched) {
return false;
}
delimiterMatched = true;
}
return isRealRecursive(string, position+1, delimiterMatched);
}
You need to use Regex. The regex to verify that whether a string holds a float number is:
^[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?$
Can anybody give me a tip on how to do this?
Starting with your existing recursive matcher for whole numbers, modify it and use it in another method to match the whole numbers in:
["+"|"-"]<whole-number>["."[<whole-number>]]
Hint: you will most likely need to change the existing method to return the index of that last character matched rather than just true / false. Think of the best way to encode "no match" in an integer result.
public static boolean isReal(String str) {
boolean real = true;
boolean sawDot = false;
char c;
for(int i = str.length() - 1; 0 <= i && real; i --) {
c = str.charAt(i);
if('-' == c || '+' == c) {
if(0 != i) {
real = false;
}
} else if('.' == c) {
if(!sawDot)
sawDot = true;
else
real = false;
} else {
if('0' > c || '9' < c)
real = false;
}
}
return real;
}
This is my input verifier:
public class MyInputVerifier extends InputVerifier {
#Override
public boolean verify(JComponent input) {
String text = ((JTextField) input).getText().trim()
if (text.isEmpty() || text.length() == 0) return false;
// How verifier that if text contains digit, return false?
return true;
}
I need to recognize when text contains digit(s), it return false to me.
Is there any method Or i should use old way?(for loop)
This is one way of checking if text contains a digit:
boolean containsADigit = text.matches(".*\\d.*");
If you want to check if all characters are digits you can still use regular expressions, or try parsing the string as an integer:
boolean isDigitsOnly = text.matches("\\d*");
Using only very basic stuff:
public boolean containsDigit(String str) {
int n = str.size();
for(int i=1, i<n, ++i) {
if(str.charAt(i).isDigit()) {return true;}
}
return false;
}
Are you looking for a more faster way?
private boolean hasOnlyDigits(String str) {
for(int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (c < '0' || c > '9') {
return false;
}
}
return true;
}
I'm trying to solve this CodingBat problem:
Return true if the given string contains an appearance of "xyz" where the xyz is not directly preceeded by a period (.). So "xxyz" counts but "x.xyz" does not.
xyzThere("abcxyz") → true
xyzThere("abc.xyz") → false
xyzThere("xyz.abc") → true
My attempt:
public boolean xyzThere(String str) {
boolean res = false;
if(str.contains(".xyz") == false && str.contains("xyz")){
res = true;
}
return res;
}
The problem is that is passes all the tests except the one below because it contains two instances of xyz:
xyzThere("abc.xyzxyz")
How can I make it pass all tests?
public static boolean xyzThere(String str) {
int i = -1;
while ((i = str.indexOf("xyz", i + 1 )) != -1) {
if (i == 0 || (str.charAt(i-1) != '.')) {
return true;
}
}
return false;
}
Alternatively, you could replace all occurrences of ".xyz" in the string with "", then use the .contains method to verify that the modified string still contains "xyz". Like so:
return str.replace(".xyz", "").contains("xyz");
public boolean xyzThere(String str) {
return(!str.contains(".xyz") && str.contains("xyz"));
}
Edit: Given that ".xyzxyz" should return true, the solution should be:
public boolean xyzThere(String str) {
int index = str.indexOf(".xyz");
if(index >= 0) {
return xyzThere(str.substring(0, index)) || xyzThere(str.substring(index + 4));
} else return (str.contains("xyz"));
}
The below code worked fine for me:
if '.xyz' in str:
return xyz_there(str.replace('.xyz',''))
elif 'xyz' in str:
return True
return False
Ok, I know everyone is eager to share their expertise but straight giving the kid the answer does little good.
#EnTHuSiAsTx94
I was able to pass all of the tests with three statements. Here is a hint: Try using the string replace method. Here is the method signature:
String replace(CharSequence target, CharSequence replacement)
On a minor note, the first condition in your if statement can be simplified from:
str.contains(".xyz") == false
to:
!str.contains(".xyz")
The contains method already returns true or false, so there is no need for the explicit equals comparison.
public boolean xyzThere(String str) {
return str.startsWith("xyz") || str.matches(".*[^.]xyz.*");
}
You can use the equivalent java code for the following solution:
def xyz_there(str):
pres = str.count('xyz')
abs = str.count('.xyz')
if pres>abs:
return True
else:
return False
Ok, let's translate your question into a regexp:
^ From the start of the string
(|.*[^\.]) followed by either nothing or any amount of any chars and and any char except .
xyz and then xyz
Java code:
public static boolean xyzThere(String str) {
return str.matches("^(|.*[^\\.])xyz");
}
boolean flag = false;
if(str.length()<=3){
flag = str.contains("xyz");
}
for (int i = 0; i < str.length()-3; i++) {
if (!str.substring(i, i+3).equals("xyz") &&
str.substring(i, i+4).equals(".xyz")) {
flag=false;
}else{
if(str.contains("xyz")) flag=true;
}
}
return flag;
public boolean xyzThere(String str) {
boolean res=false;
if(str.length()<3)res=false;
if(str.length()==3){
if(str.equals("xyz"))res=true;
else res=false;
}
if(str.length()>3){
for(int i=0;i<str.length()-2;i++){
if(str.charAt(i)=='x' && str.charAt(i+1)=='y' && str.charAt(i+2)=='z'){
if(i==0 || str.charAt(i-1)!='.')res=true;
}
}
}
return res;
}
public class XyzThereDemo {
public static void main(String[] args) {
System.out.println(xyzThere("abcxyz"));
System.out.println(xyzThere("abc.xyz"));
System.out.println(xyzThere("xyz.abc"));
}
public static boolean xyzThere(String str) {
int xyz = 0;
for (int i = 0; i < str.length() - 2; i++) {
if (str.charAt(i) == '.') {
i++;
continue;
}
String sub = str.substring(i, i + 3);
if (sub.equals("xyz")) {
xyz++;
}
}
return xyz != 0;
}
}
Another method
public boolean xyzThere(String str) {
if(str.startsWith("xyz")) return true;
for(int i=0;i<str.length()-3;i++) {
if(str.substring(i+1,i+4).equals("xyz") && str.charAt(i)!='.') return true;
}
return false;
}
public boolean xyzThere(String str) {
if (str.startsWith("xyz")){
return true;
}
for (int i = 0; i < str.length()-2; i++) {
if (str.subSequence(i, i + 3).equals("xyz") && !(str.charAt(i-1) == '.')) {
return true;
}
}
return false;
}
This is the best possible and easiest way to solve this question with very simple logic:
def xyz_there(str):
for i in range(len(str)):
if str[i-1]!= '.' and str[i:i+3]=='xyz' :
return True
return False
public boolean xyzThere(String str) {
boolean flag = false;
if (str.startsWith("xyz"))
{
return true;
}
for (int i = 0; i < str.length() - 3; i++)
{
if (str.charAt(i) != '.' && str.charAt(i + 1) == 'x'
&& str.charAt(i + 2) == 'y' && str.charAt(i + 3) == 'z')
{
flag = true;
break;
}
}
return flag;
}
def xyz_there(str1):
for i in range(len(str1)):
if str1[i-1] != '.' and str1[i:i+3] == 'xyz':
return True
else:
return False
def xyz_there(str):
if '.xxyz' in str:
return'.xxyz' in str
if '.' in str:
a=str.replace(".xyz","")
return 'xyz' in a
if '.' not in str:
return 'xyz' in str
'''python
def xyz_there(str):
dot=str.find('.') # if period is present in str if not dot==-1
if dot==-1: # if yes dot will show position of period
return 'xyz' in str
elif dot!=-1: #if period is present at position dot
if 'xyz' in str[:dot]:
return True
while str[dot+1:].find('.')!=-1: #while another period is present
if '.xyz' in str[dot+1:]==False: # .xyz will not be counted
return True
else:
dot=dot+str[dot+1:].find('.')+2 #now dot=previous dot+new dot+2
else:
return 'xyz' in str[dot+2:]
'''
def xyz_there(str):
list = [i for i in range(len(str)) if str.startswith('xyz', i)]
if list == []:
return False
else:
found = 0
for l in list:
if str[l-1:l+3] != ".xyz":
found += 1
if found >=1:
return True
else:
return False
simple solution just by replace and check the "xyz " in a thats it
def xyz_there(str):
a=str.replace('.xyz','')
return 'xyz' in a
This is the question:
Problem I.
We define the Pestaina strings as follows:
ab is a Pestaina string.
cbac is a Pestaina string.
If S is a Pestaina string, so is SaS.
If U and V are Pestaina strings, so is UbV.
Here a, b, c are constants and S,U,V are variables. In these rules,
the same letter represents the same string. So, if S = ab, rule 3
tells us that abaab is a Pestaina string. In rule 4, U and V represent
Grandpa strings, but they may be different.
Write the method
public static boolean isPestaina(String in)
That returns true if in is a Pestaina string and false otherwise.
And this is what i have so far which only works for the first rule, but the are some cases in which doesnt work for example "abaaab":
public class Main {
private static boolean bool = true;
public static void main(String[] args){
String pestaina = "abaaab";
System.out.println(pestaina+" "+pestainaString(pestaina));
}
public static boolean pestainaString(String p){
if(p == null || p.length() == 0 || p.length() == 3) {
return false;
}
if(p.equals("ab")) {
return true;
}
if(p.startsWith("ab")){
bool = pestainaString(p, 1);
}else{
bool = false;
}
return bool;
}
public static boolean pestainaString(String p, int sign){
String letter;
char concat;
if("".equals(p)){
return false;
}
if(p.length() < 3){
letter = p;
concat = ' ';
p = "";
pestainaString(p);
}else if(p.length() == 3 && (!"ab".equals(p.substring(0, 2)) || p.charAt(2) != 'a')){
letter = p.substring(0, 2);
concat = p.charAt(2);
p = "";
pestainaString(p);
}else{
letter = p.substring(0, 2);
concat = p.charAt(2);
pestainaString(p.substring(3));
}
if(letter.length() == 2 && concat == ' '){
if(!"ab".equals(letter.trim())){
bool = false;
//concat = 'a';
}
}else if((!"ab".equals(letter)) || (concat != 'a')){
bool = false;
}
System.out.println(letter +" " + concat);
return bool;
}
}
Please tell me what i have done wrong.
I found the problem i was calling the wrong method.
You are describing a Context Free Language, which can be described as a Context Free Grammer and parsed with it. The field of parsing these is widely researched and there is a lot of resources for it out there.
The wikipedia page also discusses some algorithms to parse these, specifically - I think you are interested in the Early Parsers
I also believe this "language" can be parsed using a push down automaton (though not 100% sure about it).
public static void main(String[] args) {
// TODO code application logic here
String text = "cbacacbac";
System.out.println("Is \""+ text +"\" a Pestaina string? " + isPestaina(text));
}
public static boolean isPestaina(String in) {
if (in.equals("ab")) {
return true;
}
if (in.equals("cbac")) {
return true;
}
if (in.length() > 3) {
if ((in.startsWith("ab") || in.startsWith("cbac"))
&& (in.endsWith("ab") || in.endsWith("cbac"))) {
return true;
}
}
return false;
}
That was fun.
public boolean isPestaina(String p) {
Set<String> existingPestainas = new HashSet<String>(Arrays.asList(new String[]{"ab", "cbac"}));
boolean isP = false;
int lengthParsed = 0;
do {
if (lengthParsed > 0) {
//just realized there's a touch more to do here for the a/b
//connecting rules...I'll leave it as an excersize for the readers.
if (p.substring(lengthParsed).startsWith("a") ||
p.substring(lengthParsed).startsWith("b")) {
//good connector.
lengthParsed++;
} else {
//bad connector;
return false;
}
}
for (String existingP : existingPestainas) {
if (p.substring(lengthParsed).startsWith(existingP)) {
isP = true;
lengthParsed += existingP.length();
}
}
if (isP) {
System.err.println("Adding pestaina: " + p.substring(0, lengthParsed));
existingPestainas.add(p.substring(0, lengthParsed));
}
} while (isP && p.length() >= lengthParsed + 1);
return isP;
}