Parsing Java String type Error - java

What i'm trying to do is incorporate interface methods to complete a task given the variables inside of a string. The string i'm given, "s" can be made up numbers, +, -, and * symbols. The integer return is fairly easy as all i'm doing is returning an integer interface method of that int. However, for the other 3 symbols, I need to recursively incorporate a method to find the left and right nodes. I've posted my code below...
public static Expression parseString( String s ) {
String[] parse = s.split("\\s+");
String[] parsecopy;
Expression exp1;
Expression exp2;
if(s == null) {
return null;
}
if(parse[0].equals("+")) {
exp1 = parseString(parse[0]);
parsecopy = Arrays.copyOfRange(parse, 2, parse.length);
exp2 = parseString(parsecopy);
return new AddExpression(exp1, exp2);
}
else if() {
The problem - So my code creates a copy of the original string to find the next item in that string. I do this by using the Array function, copyOfRange(). However, when I want to call exp2 = parseString(parsecopy), i'm receiving an error because parseString takes in a string argument which has to be of the type String[]. The reason i'm trying to get parsecopy instead of parsecopy[0] is because parsecopy wouldn't create an endless loop and I would actually be able to iterate through the string.
Error code - The method parseString(String) in the type Parse is not applicable for the arguments (String[])

if(parse[0].equals("+")) {
exp1 = parseString(parse[0]);
parsecopy = Arrays.copyOfRange(parse, 2, parse.length);
exp2 = parseString(parsecopy);
return new AddExpression(exp1, exp2);
}
exp1 = parseString(parse[0]);
you are doing recursive calling here.

Since the parameter you pass to split is a regex, you can simply do:
String[] ss = "12121+34234 *23423 -123123 *123123-12312+1231231-123123".split("\\s?[\\+\\-\\*]\\s?");
this way you split your string wherever you got a +, - , or * (possibly with a whitespace after or before).
And please do the null-check of the string before split it :D
Hope it helps.

It seems like you want to check parse[1] equals "+" rather than parse[0].
You would expect 1 + 2 rather than + 1 2.

Related

java I thought strings were immutable

I was always told strings in java are immutable, unless your going to use the string builder class or string writter class.
Take a look at this practice question I found online,
Given a string and a non-negative int n, return a larger string that is n copies of the original string.
stringTimes("Hi", 2) → "HiHi"
stringTimes("Hi", 3) → "HiHiHi"
stringTimes("Hi", 1) → "Hi"
and the solution came out to be
Solution:
public String stringTimes(String str, int n) {
String result = "";
for (int i=0; i<n; i++) {
result = result + str; // could use += here
}
return result;
}
As you see in the solution our 3rd line assigns the string , then we change it in our for loop. This makes no sense to me! (I answered the question in another nooby way ) Once I saw this solution I knew I had to ask you guys.
Thoughts? I know im not that great at programming but I haven't seen this type of example here before, so I thought I'd share.
The trick to understanding what's going on is the line below:
result = result + str;
or its equivalent
result += str;
Java compiler performs a trick on this syntax - behind the scene, it generates the following code:
result = result.concat(str);
Variable result participates in this expression twice - once as the original string on which concat method is called, and once as the target of an assignment. The assignment does not mutate the original string, it replaces the entire String object with a new immutable one provided by concat.
Perhaps it would be easier to see if we introduce an additional String variable into the code:
String temp = result.concat(str);
result = temp;
Once the first line has executed, you have two String objects - temp, which is "HiHi", and result, which is still "Hi". When the second line is executed, result gets replaced with temp, acquiring a new value of "HiHi".
If you use Eclipse, you could make a breakpoint and run it step by step. You will find the id (find it in "Variables" View) of "result" changed every time after java did
result = result + str;
On the other hand, if you use StringBuffer like
StringBuffer result = new StringBuffer("");
for(int i = 0; i < n; i++){
result.append(str);
}
the id of result will not change.
String objects are indeed immutable. result is not a String, it is a reference to a String object. In each iteration, a new String object is created and assigned to the same reference. The old object with no reference is eventually destroyed by a garbage collector. For a simple example like this, it is a possible solution. However, creating a new String object in each iteration in a real-world application is not a smart idea.

Splitting a string by delimiter without any variables?

Can you split a string in Java without storing what has been split into variables? (Assignment requirement :()
I have tried things which worked on other programming languages however nothing I try seems to work:
(Attempting to see if the second item in a space delimited string (x) is +)
if ((x.split.(" ")).(1) = "+") {
// Do something
}
if ((x.split.(1).(" ")) = "+") {
// Do something
}
Well, what is returned is of type String[]. So if you know that there will be two items, you can reference it as an array..
if(x.split(" ")[1].equals("+"))
Extra Reading
You should look at String Comparison.
String.split returns an array, so this is how it could be done. Note the use of '.equals()'. In Java the == operator checks if the pointer value is the same.
if (x.split.(" ")[1].equals("+")) {
// Do something
}
(And of course this could throw an out of bounds exception if the split wouldn't make an array of size >= 2)

Java: split; cannot convert string[] to string

I'm trying to set up a program that prompts the user to enter a math equation only containing addition and place it in parentheses. My code is meant to search for these equations and give back the sum of the equation.
The part I am having trouble with is when I try to split the addition signs from the code, and parse it so I can turn it into a int. But when I try to split, I get an error that says cannot convert String[] to String.
Here is the coding I have thus far:
String userinput = in.nextLine();
int parentheses;
int parenthesesclose, parse;
String usersubstring;
String split;
while (parentheses >= 0) {
parentheses = userinput.indexOf("(");
parenthesesclose = userinput.indexOf(")");
usersubstring = userinput.substring(parentheses + 1, parenthesesclose);
split = usersubstring.split(+);
split.trim();
if (split.isdigit) {
parse = Interger.parseInt(split);
}
}
Exactly as the error message tells you, String#split() returns a String[], which is a string array. Change your declaration to this:
String[] split;
You should declare variable split as String[]. split() will return you an array of Strings.
String userinput=in.nextLine();
int parentheses;
int parenthesesclose, parse;
String usersubstring;
String[] split;
while ( parentheses >= 0){
parentheses = userinput.indexOf("(");
parenthesesclose = userinput.indexOf(")");
usersubstring = userinput.substring( parentheses + 1, parenthesesclose);
split = usersubstring.split("+");
}
Method split returns an string array, so you should change the type of your split variable to an array.
Also, the multiply symbol not in brakets.
Is this declaration of variables local? If yes, you should define them, otherwise there are possible errors in the heap.

How can I match a char at a specific index in a string?

I have a simple string that I'm trying to determine if a specific index results in a specific char.
I'm trying to do it like this (but I get compilation errors):
if(myString.charAt(7).equals("/")) {
// do stuff
} else {
// do other stuff
}
Error:
Type mismatch: cannot convert from char to boolean
(myString.charAt(7).equals("/")
should be following because charAt() returns char:
myString.charAt(7) == '/'
if(myString.charAt(7)== '/') {
// do stuff
} else {
// do other stuff
}
Putting a character in double quotes makes it a String. Single quotes makes it a char. And you compare characters with literal == whereas you compare Objects with the equals method
There's a couple solutions on this answer that give you what you were probably trying to do, which is compare a single character to another single character. I won't go over that because they've done excellently.
But you can still use a String if you like, and prepare for the future. (Perhaps "/" changes to "//"?) you can do this:
if(myString.substring(7,8).equals("/")) {
// stuff
}
Then down the road you might be like
public static final String SEPARATOR_STRING = "//";
public static final int SEPARATOR_START = 7;
public static final int SEPARATOR_END = 7 + SEPARATOR_STRING.length();
// later
if(myString.substring(SEPARATOR_START,7SEPARATOR_END).equals(SEPARATOR_STRING)) {
// stuff
}
charAt() returns char, not object, so you need to compare it that way:
if(myString.charAt(7)== '/') {
...
note the single quote around /.
if(myString.substring(7,8).equals("/"))
or
if(myString.charAt(7)=='/')
or
if(myString.indexOf("/"))==7) can be use

First char to upper case [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to upper case every first letter of word in a string?
Most efficient way to make the first character of a String lower case?
I want to convert the first letter of a string to upper case. I am attempting to use replaceFirst() as described in JavaDocs, but I have no idea what is meant by regular expression.
Here is the code I have tried so far:
public static String cap1stChar(String userIdea)
{
String betterIdea, userIdeaUC;
char char1;
userIdeaUC = userIdea.toUpperCase();
char1 = userIdeaUC.charAt(0);
betterIdea = userIdea.replaceFirst(char1);
return betterIdea;
}//end cap1stChar
The compiler error is that the argument lists differ in lengths. I presume that is because the regex is missing, however I don't know what that is exactly.
Regular Expressions (abbreviated "regex" or "reg-ex") is a string that defines a search pattern.
What replaceFirst() does is it uses the regular expression provided in the parameters and replaces the first result from the search with whatever you pass in as the other parameter.
What you want to do is convert the string to an array using the String class' charAt() method, and then use Character.toUpperCase() to change the character to upper case (obviously). Your code would look like this:
char first = Character.toUpperCase(userIdea.charAt(0));
betterIdea = first + userIdea.substring(1);
Or, if you feel comfortable with more complex, one-lined java code:
betterIdea = Character.toUpperCase(userIdea.charAt(0)) + userIdea.substring(1);
Both of these do the same thing, which is converting the first character of userIdea to an upper case character.
Or you can do
s = Character.toUpperCase(s.charAt(0)) + s.substring(1);
public static String cap1stChar(String userIdea)
{
char[] stringArray = userIdea.toCharArray();
stringArray[0] = Character.toUpperCase(stringArray[0]);
return userIdea = new String(stringArray);
}
Comilation error is due arguments are not properly provided, replaceFirst accepts regx as initial arg. [a-z]{1} will match string of simple alpha characters of length 1.
Try this.
betterIdea = userIdea.replaceFirst("[a-z]{1}", userIdea.substring(0,1).toUpperCase())
String toCamelCase(String string) {
StringBuffer sb = new StringBuffer(string);
sb.replace(0, 1, string.substring(0, 1).toUpperCase());
return sb.toString();
}
userIdeaUC = userIdea.substring(0, 1).toUpperCase() + userIdea.length() > 1 ? userIdea.substring(1) : "";
or
userIdeaUC = userIdea.substring(0, 1).toUpperCase();
if(userIdea.length() > 1)
userIdeaUC += userIdea.substring(1);
For completeness, if you wanted to use replaceFirst, try this:
public static String cap1stChar(String userIdea)
{
String betterIdea = userIdea;
if (userIdea.length() > 0)
{
String first = userIdea.substring(0,1);
betterIdea = userIdea.replaceFirst(first, first.toUpperCase());
}
return betterIdea;
}//end cap1stChar

Categories