Verify if String matches real number - java

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

Related

check if char[] contains only one letter and one int

I have no idea how to check if char[] contains only one letter (a or b) on the first position and only one int (0-8) on the second position. for example a2, b2
I have some this, but I do not know, what should be instead of digital +=1;
private boolean isStringValidFormat(String s) {
boolean ret = false;
if (s == null) return false;
int digitCounter = 0;
char first = s.charAt(0);
char second = s.charAt(1);
if (first == 'a' || first == 'b') {
if (second >= 0 && second <= '8') {
digitCounter +=1;
}
}
ret = digitCounter == 2; //only two position
return ret;
}
` public char[] readFormat() {
char[] ret = null;
while (ret == null) {
String s = this.readString();
if (isStringValidFormat(s)) {
ret = s.toCharArray();
}else {
System.out.println("Incorrect. Values must be between 'a0 - a8' and 'b0 - b8'");
}
}
return new char[0];
}`
First, I would test for null and that there are two characters in the String. Then you can use a simple boolean check to test if first is a or b and the second is between 0 and 8 inclusive. Like,
private boolean isStringValidFormat(String s) {
if (s == null || s.length() != 2) {
return false;
}
char first = s.charAt(0);
char second = s.charAt(1);
return (first == 'a' || first == 'b') && (second >= '0' && second <= '8');
}
For a well understood pattern, use Regex:
private static final Pattern pattern = Pattern.compile("^[ab][0-8]$")
public boolean isStringValidFormat(String input) {
if (input != null) {
return pattern.matcher(input).matches();
}
return false;
}

Recognize String has digits

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

Translating a regex into a more basic code

How can I write the below code without using regex?
public static boolean validateCode(String code){
boolean hasAtLeastOneNumber = Pattern.compile("[0-9].*[0-9]")
.matcher(code).find();
boolean hasAtLeastTwoLetters = Pattern.compile("[a-zA-Z].*[a-zA-Z]")
.matcher(code).find();
boolean hasAtLeastOneHyphen = Pattern.compile("-")
.matcher(code).find();
}
How about
public static boolean validateCode2(String code) {
int numbers = 0, letters = 0, hyphens = 0;
for (char c : code.toCharArray()) {
if (Character.isDigit(c)) numbers++;
if (Character.isAlphabetic(c)) letters++;
if (c=='-') hyphens++;
}
return numbers>=2 && letters>=2 && hyphens>=1;
}
For hasAtLeastOneNumber:
for (char c : code.toCharArray()) {
if (Character.isDigit(c)) {
return true;
}
return false;
For hasAtLeastTwoLetters:
int numFound = 0;
for (char c : code.toCharArray()) {
if (Character.isLetter(c)) {
numFound++;
if (numFound >= 2) {
return true;
}
}
}
return false;
For hasAtLeastOneHyphen:
for (char c : code.toCharArray()) {
if (c == '-') {
return true;
}
}
return false;
If you don't want to use toCharArray, you could use:
for (int i=0; i<code.length(); i++) {
char c = code.charAt(i);
// do the rest of the test here
}
That's basically equivalent to using toCharArray except that it's slightly more confusing: someone who looks at the code would need to take a second or two to figure it out. With toCharArray it's obvious what you're doing.
You can loop through the string and test it for ranges of characters. See an example on IDEONE, or ask me if you need an explanation.
import java.util.*;
import java.lang.*;
class Main
{
public static void main (String[] args) throws java.lang.Exception
{
System.out.println(validarCodigo("No-numbers"));
System.out.println(validarCodigo("1-A"));
System.out.println(validarCodigo("This 1 Matches -- :-)"));
}
public static boolean validarCodigo(String codigo) {
int i;
char[] chars = codigo.toCharArray();
char current;
boolean tieneAlmenosUnNumero = false;
boolean tieneAlmenosDosLetras = false;
boolean tieneAlmenosUnGuion = false;
// Check for at least one number
for (i=0; i<chars.length; i++) {
current = chars[i];
if (current >= '0' && current <= '9') {
tieneAlmenosUnNumero = true;
break;
}
}
// Check for at least two letters
int found = 0;
for (i=0; i<chars.length; i++) {
current = chars[i];
boolean lower = current >= 'a' && current <= 'z';
boolean upper = current >= 'A' && current <= 'Z';
if (lower || upper) found++;
if (found == 2){
tieneAlmenosDosLetras = true;
break;
}
}
// Check for at least one hyphen
for (i=0; i<chars.length; i++) {
current = chars[i];
if (current == '-') {
tieneAlmenosUnGuion = true;
break;
}
}
return tieneAlmenosUnNumero && tieneAlmenosDosLetras && tieneAlmenosUnGuion;
}
}

Return true if string cointains "xyz" not preceeded by a period?

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

java homework(recursion)

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

Categories