Validating input string with java - java

First off, I will admit that this is an assignment of mine. however, I am at my wits end. I tried need to validate that the user input a proper expression (ie: "7 + 5;") and I managed to do it with split methods but I was told that I can't do that. I'm sure there is a simple solution to the problem but I am not seeing it.
The code is rather lengthy so I won't post it but if I will if needed.
Thanks!
Edit to answer questions: I am writing in jGrasp, so they can do whatever is on the keyboard. I was told to "Find a creative way to use substrings" which I don't know what that means. The expression needs to be Number Space operand Space number semicolon
here is what I have for the validation... I am using arrays for each character in the expression
public static boolean validFormat(String expr)
{
String tokens[] = expr.substring()
if (tokens.length == 3)
{
if (tokens[0].equals(""))
{
return false;
}
if (tokens[1].equals(""))
{
return false;
}
if (tokens[2].length < 2)
{
return false;
}
else
{
if (tokens[2].endwith(";"));
{
return false;
}
else
{
return true;
}
}
}
return false;
}
I get an error with calling the substring as well as an "else without if" error

First, you should limits the input to 6 characters using an if statement. Then use the CharAt() method to return each character to check the condition.

I was told to "Find a creative way to use substrings".
As told, try using String.substring() for the same.
public class Demo {
public static void main (String[] args) {
String exp = "7 + 5;";
System.out.printf("%s\t%b%n", exp, validate(exp));
exp = "4 + d;";
System.out.printf("%s\t%b%n", exp, validate(exp));
}
public static boolean validate(String exp) {
String n1 = exp.substring(0,1);//operand
String n2 = exp.substring(4,5);//operand
String co = exp.substring(5);//semicolon
String s1 = exp.substring(1,2);//space
String s2 = exp.substring(3,4);//space
String op = exp.substring(2,3);//operator
return num(n1) && num(n2) && semi(co) && space(s1) && space(s2) && opt(op);
}
public static boolean num(String n) {
return "0123456789".contains(n);
}
public static boolean semi(String s) {
return ";".equals(s);
}
public static boolean space(String s) {
return " ".equals(s);
}
public static boolean opt(String s) {
return "-+*%/^".contains(s);
}
}
This solution uses RegExp:
public class Demo {
public static void main (String[] args) {
String exp = "7 + 5;";
System.out.printf("%s\t%b%n", exp, validate(exp));
exp = "4 + d;";
System.out.printf("%s\t%b%n", exp, validate(exp));
}
public static boolean validate(String exp) {
return exp.matches("\\d\\s(\\+|\\-|\\*|\\/|\\^|\\%)\\s\\d\\;");
}
}

Related

Getting previous return value with new value concatenated using recursion

I'm working a problem on recursion. After writing the code requested, the site I'm working from runs the code with different values as input. However, the first run works properly, but all subsequent runs concatenate the return value of the first run with the values of each of the subsequent runs.
I am also getting a stack overflow error at the end.
I need help!
Here is the code:
package com.company;
import static java.lang.System.*;
public class Main {
public static String returnValue="";
public static void main(String[] args) {
repeat("this is fun", 1);
out.println(returnValue);
}
public static String repeat(String s, int i){
if (i==0) {
return returnValue;
}
else{
returnValue+=s;
repeat(s,i-1);
}
return returnValue;
}
}
Any help is greatly appreciated.
You need to move the static returnValue into the method. You then need to control the result by capturing the string returned by the inner recursive call.
Something like:
public static String repeat(String s, int i){
String returnValue="";
if (i==0) {
return returnValue;
}
else{
returnValue+=s + repeat(s,i-1);
}
return returnValue;
}
NB: This may not be the equivalent algorithm to what you intend but it should demonstrate the technique.
If that is the correct solution then you can tidy up with:
public static String repeat(String s, int i){
if (i==0) {
return "";
} else {
return s + repeat(s,i-1);
}
}
If you are comfortable with expressions:
public static String repeat(String s, int i) {
return i <= 0
? ""
: s + repeat(s, i - 1);
}
and you can get rid of the static attribute!

"unreachable statement" in a boolean recursion

I need to write a short recursive program for a class that checks if a string - t is transformation of another string - s. It simply needs to check if every character in s is also in t.
For ex:
"sddbs" is not a transformation of "sdb"
"sddbs" is a transformation of "sddb".
public static boolean isTrans (String s, String t)
{
if (t.indexOf(s.charAt(0)) != -1)
return true;
else
return false;
return isTrans(s.substring(1), t);
}
And still.. the code doesn't work as expected. "unreachable statement" in the last line of the code.
The reason is quite simple:
there is no possible way to execute this line:
return isTrans(s.substring(1), t);
why?:
you have a return IF this condition (t.indexOf(s.charAt(0)) != -1) is met and another if not....
It's because of the Law of Excluded Middle. You can treat return as exit function.
public static boolean isTrans (String s, String t) {
if (condition)
return true;
else
return false;
//the condition must have been true or false so the method has already exited.
return isTrans(s.substring(1), t);
}
If the condition is true, you return true, if it's false you return false. Otherwise you call recursively. There is no otherwise.
You final return statement is unreachable because your method body contains return statement for both if and else condition, hence assuring that the last return statement will never be reached.
But besides this I don't understand why you need to write a recursive function, though a non-recursive function using similar method calls will do the same thing:
public static boolean isTrans (String s, String t)
{
if (t.indexOf(s) > -1)
return true;
else
return false;
}
Edit:
As suggested by #Holger you can avoid unnecessary if else and replace your code with:
public static boolean isTrans (String s, String t)
{
return (t.indexOf(s) > -1) //returns true or false just like your if else
}
or even shorter:
public static boolean isTrans (String s, String t)
{
return t.contains(s); //internally contains() calls indexOf(), similar to what you are doing
}
According to your recursion method once you enter the if condition it would either return a true or false output. so your code never reaches the recursion statement.
I would like to suggest my way of implementing your transformation program using recursion.
import java.util.Scanner;
public class Recursion {
static int flag;
public void isTransformation(String str1, String str2) {
flag = str2.length();
char ch1[], ch2[];
ch1 = str1.toCharArray();
ch2 = str2.toCharArray();
if (ch1[0] == ch2[0]) {
flag--;
if (flag == 0) {
System.out.println("Transformation");
return;
}
isTransformation(str1.substring(1), str2.substring(1));
} else
System.out.println("Not a Transformation");
}
public static void main(String args[]) {
String str1, str2;
Scanner sc = new Scanner(System.in);
System.out.print("Enter string 1: ");
str1 = sc.nextLine();
System.out.print("Enter string 2: ");
str2 = sc.nextLine();
Recursion r = new Recursion();
if (str1.length() >= str2.length())
r.isTransformation(str1, str2);
else
r.isTransformation(str2, str1);
sc.close();
}
}

calculate the number of characters in a string recursively

I am trying to calculate the number of characters in a string by using recursive method. here is my code in java
public class MainClass {
public int length(String str) {
if (str == null) {
return 0;
} else {
return length(str.substring(1))+1; // in eclipse it says : at MainClass.length(MainClass.java:12)
}
}
public static void main(String args[]) {
MainClass m = new MainClass();
System.out.println(m.length("ali"));
}
}
This line does not work : return length(str.substring(1))+1;
How can I correct the code?
Thanks
You forgot the case when your String argument is an empty string, include that in your check:
if (str == null || str.length()==0) {
return 0;
} else {
[...]
Please note that the Exception that you get contains valuable information about what's going wrong, in this case it's probably a StringIndexOutOfBoundsException because you call substring(1) on an empty String object.
It should be
public int length(String str) {
if (str==null||str.isEmpty()) {
return 0;
}else {
return length(str.substring(1))+1
}

Java contains a string or not?

http://codingbat.com/prob/p126880
Given two strings, return true if either of the strings appears at the very end of the other string, ignoring upper/lower case differences (in other words, the computation should not be "case sensitive"). Note: str.toLowerCase() returns the lowercase version of a string.
I cannot get when it is true, it always gives false.
public boolean endOther(String a, String b)
{
//variables
a.toLowerCase();
b.toLowerCase();
String f1="";
String f2="";
int d=0;
int sum=0;
//Program code;
if(a.length()-b.length()>0)
{
(f1).equals(a);
(f2).equals(b);
d=a.length();
}
else if(a.length()-b.length()<0)
{
(f1).equals(b);
(f2).equals(a); //gett**ing bigger and lower String**
d=b.length();
}
else if((a).equals(b))
sum++;
// I think problem is because it is not enter the for.
for(int i=0; i>d; i++)
{
if((f1.substring(i,i+f2.length())).equals(f2))
sum++;
}
if(sum>0)
return true;
else
return false;
}
This is a working example of what you are trying to achieve to test in your Java IDE like Netbeans or Eclipse whatever. This is really simple, the String object has an endsWith method so why try to invent something yourself.
If you have any troubles reading this code hit me up, should be quite straight forward. You will just have to convert your string to lowercase, that's for you to add.
public class StringEnds {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.printf("String a: ");
String a = scanner.next();
System.out.printf("String b: ");
String b = scanner.next();
// Compare a and b
if (endsWith(a, b)) {
System.out.printf("Succes\n");
} else {
System.out.printf("Fail\n");
}
}
public static boolean endsWith(String firstString, String secondString) {
return firstString.endsWith(secondString) || secondString.endsWith(firstString);
}
}
Here's your codebat solution (it is quite short):
public boolean endOther(String a, String b) {
return a.toLowerCase().endsWith(b.toLowerCase()) || b.toLowerCase().endsWith(a.toLowerCase());
}
This is my answer. I tried both ways, hope it helps.
public boolean endOther(String a, String b) {
int small = Math.min(a.length(), b.length());
if (a.length()==b.length() && a.equalsIgnoreCase(b)) {
return true;
}
if (small==a.length()) {
if (b.substring(b.length()-small).equalsIgnoreCase(a)) {
return true;
}
// from here is the toLowerCase() method.
a = a.toLowerCase();
b = b.toLowerCase();
} else if (small==b.length()) {
if (a.endsWith(b)) {
return true;
}
}
return false;
}

Error in my Word program in Java

This is my code and it compiles fine but when I try to create a string it says
Error: cannot find symbol - variable racer
public class Word {
private String original;
public Word(String s) {
original = s;
}
public String reverse () {
String reverse= "";
int x = 1;
int length = original.length();
while (length - x >= 0) {
reverse = reverse + original.substring(length -x);
x++;
}
return reverse;
}
public boolean isPalindrome() {
if(original.equals(reverse()))
return true;
else
return false;
}
}
The stated problem is not in the code posted - my guess is irrelephant's comment is correct, ie change new Word(racer) --> new Word("racer").
But I offer this to eliminate any chance of any errors in your code by basically eliminating your code:
public class Word {
private String original;
public Word(String s) {
original = s;
}
public boolean isPalindrome()
return new StringBuilder(original).reverse().toString().equals(original);
}
}
or if you must expose a reverse() method:
public class Word {
private String original;
public Word(String s) {
original = s;
}
public String reverse () {
return new StringBuilder(original).reverse().toString();
}
public boolean isPalindrome()
return reverse().equals(original);
}
}
I don't see the variable racer anywhere, but since you're using reverse inside a method, I'd recommend making it
Most likely, racer was never defined
Either that or the method was called w/o quotes
isPalindrome(racer)//note the lack of quotes
change reverse() to this
private() String reverse () {
String reverse= "";
int x = 1;
int length = original.length();
while (length - x >= 0) {
reverse = reverse + original.substring(length -x);
x++;
}
return reverse;

Categories