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.
Related
I'm trying to separate the arrays and variables from an expression so that I can populate two ArrayLists with either array names or variables. I am using StringTokenizer. I have the expression broken down, but I am having trouble determining which tokens are array names and which are variables.
public void buildSymbols() {
String s = expr; // input from different part of the program
StringTokenizer st = new StringTokenizer(s, "+-*/[]() ");
while(st.hasMoreElements()){
String temp = st.nextToken();
System.out.println(temp);
}
}
I print temp just to make sure that the expression is being separated, but given an expression such as (varx + vary * varz[(vara + varb[(a + b) * 33])]) / 55 I don't know how to tell that varz and varb are array names, while varx, vary, vara, a, and b are variables.
Any ideas how to do this?
I agree wih EJP: The correct solution would be a specific parser. But if you would be content to recognize which delimitter was found by each call to StringTokenizer.nextToken, you can tell StringTokenizer to return also the delimitters. Also, you'll need to retrieve the next delimitter on every current token (as a lookahead). To do that, it's better to store all the tokens in a list:
public void buildSymbols() {
String s = expr; // input from different part of the program
StringTokenizer st = new StringTokenizer(s, "+-*/[]() ", true);
Set<String> delimiters=new HashSet<String>(Arrays.asList(new String[]{"+","-","*","/","[","]","(",")"," "}));
List<Object> tokens=Collections.list(st);
for(int i=0;i<tokens.size();i++){
String temp = tokens.get(i).toString();
if (delimiters.contains(temp))
{
// It is a delimiter
}
else
{
// It is a term
boolean isAnArray=(isNextTokenAnOpenBracket(tokens, i));
...
}
System.out.println(temp);
}
}
private boolean isNextTokenAnOpenBracket(List<Object> tokens, int currentIndex)
{
return (currentIndex < tokens.size() && "[".equals(tokens.get(1 + currentIndex)));
}
Try the String .split() method. It is an alternative to string tokenizer. You can split a string into an array of smaller strings split by a delimiter, just like StringTokenizer. However, you could do it two separate times, the first being with brackets, and the second with the other symbols. Then you know that the last index of your String arrays are the names of Arrays!
String s = expr;
String[] brackSplit = s.split("\\[");
for (String str : brackSplit) {
String[] finalSplit = str.split("*+-/()");
//finalSplit[finalSplit.length - 1] = Array Name!
}
NOTE: StringTokenizer is becoming deprecated with the new version of Java. The string split() method has become the new "recommended" way of splitting strings by delimiters.
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.
I am trying to place spaces in between a number that has been entered in a textfield. I am using the following code:
for(int i = 0; i <= 2; i++)
{
char cijfer = tf1.getText().charAt(i);
char getal1 = tf1.getText().charAt(0);
char getal2 = tf1.getText().charAt(1);
char getal3 = tf1.getText().charAt(2);
}
String uitvoerGetal = getal1 + " " + getal2 + " " + getal3;
I suppose I don't understand the charAt() function yet, does anyone have a link explaining it in a way so I might be able to make this work too? Thanks in advance!
Example:
public class Test {
public static void main(String args[]) {
String s = "Strings are immutable";
char result = s.charAt(8);
System.out.println(result);
}
}
This produces the following result:
a
In more Detail From java docs
public char charAt(int index)
Returns the char value at the specified index. An index ranges from 0 to length() - 1. The first char value of the sequence is at index 0, the next at index 1, and so on, as for array indexing.
If the char value specified by the index is a surrogate, the surrogate value is returned.
Specified by:
charAt in interface CharSequence
Parameters:
index - the index of the char value.
Returns:
the char value at the specified index of this string. The first char value is at index 0.
Throws:
IndexOutOfBoundsException - if the index argument is negative or not less than the length of this string.
In straight words You can't. You can't add space in int datatype because int is meant to store the integer value only. Change int to String to store the space in between.
Okay, let's see what's wrong with your code...
Your for-loop is 1-based instead of the standard 0-based. That's not good at all.
You're attempting to assign a char to a String (3 times), the first call to charAt is correct, but for some reason you then switch to using a String?
Finally you're attempting to assign a String to an int, which is just completely nonsensical.
You have a number of problems, but well done on an honest attempt.
First up, the indexes in a string are zero-based, so charAt(0) gives you the first character, charAt(1) gives you the second character, and so on.
Secondly, repeating all your calls to charAt three times is probably unnecessary.
Thirdly, you must be careful with your types. The return value from charAt is a char, not a String, so you can't assign it to a String variable. Likewise, on the last line, don't assign a String to an int variable.
Lastly, I don't think you've thought about what happens if the text field doesn't contain enough characters.
Bearing these points in mind, please try again, and ask for further help if you need it.
Try following code
String text = tf1.getText(); // get string from jtextfield
StringBuilder finalString = new StringBuilder();
for(int index = 0; index <text.length(); index++){
finalString.append(text.charAt(index) + " "); // add spaces
}
tf1.setText(finalString.toString().trim()) // set string to jtextfield
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
I have to do this for an assignment in my java class. I have been searching for a while now, but only find solutions with regex etc.
For my assignment however I may only use charAt(), length() and/or toCharArray(). I need to get from a string like gu578si300 for example just the numbers so it will become: 578300.
i know numbers are 48 - 57 in ASCII but i can't figure out how to do this in java. You guys any ideas?
i was thinking about a for loop that checks whether the (int) char is between 48-57 en if so puts the value into a seperate array. Howeevr i dont know how to programm that last thing.
I now have this;
public static String filterGetallenreeks(String reeks){
String temp = "";
for (char c : reeks.toCharArray()) {
if ((int) c > 47 && (int) c < 58)
temp += c;
}
return temp;
however it is not working, it just outputs the same as goes in.
is it something in my mainm which looks like this. If i'm right the return temp; will return the temp string into the reeks string in the main right? why is my input still the same a sthe output?
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Voer een zin, woord of cijferreeks in:");
String reeks = sc.nextLine();
if (isGetallenreeks(reeks)){
System.out.println("is getallenreeks");
filterGetallenreeks(reeks);
System.out.println(reeks);
}
Since this is homework I will not be providing the complete solution, however, this is how you should go about it:
Do a for loop that iterates for the total amount of characters within the string (.length). Check if the character is a digit using the charAt and isDigit methods.
You could do a loop that checks a character in the string, and if it's a number, append it to another string:
//I haven't tested this, so you know.
String test = "gu578si300 ";
String numbers = "";
for(int i=0; i<test.length(); i++){
if("0123456789".indexOf(test.charAt(i)) // if the character at position i is a number,
numbers = numbers + test.charAt(i); // Add it to the end of "numbers".
}
int final = Integer.parseInt(numbers); // If you need to do something with those numbers,
// Parse it.
Let me know if that works for you.
It seems like a reasonable approach, but I'd make a couple of changes from what you suggested:
If you need to result as a string then use a StringBuilder instead of an array.
Use character literals like '0' and '9' instead of ASCII codes to make your code more readable.
Update
The specific problem with your code is this line:
temp = temp + (int)c;
This converts the character to its ASCII value and then converts that to a decimal string containing the ASCII value. That's not what you want. Use this instead:
temp += c;