As part of a calulator program I am writing, I am required to have the user input all the parameters in one string and I need to extract the corresponding values from it.
For example the user enters "3 5 *" he'll get "15" back.
So the program I need to write will take '3' and assign that to double input1, '5' to double input2, and '*' to char operator. How do I get java to assign parts of a string to different members.
I was thinking of maybe splitting the user's string into multiple strings and parsing the values out but I don't know how effective that would be. Thanks in advance.
You will need to consider the order of operations if you have more then one operation. IE (3 4 +) 3 *. A common method for this would be to use a stack. Push the values onto the stack and perform the operation on the values you pop following the operation itself. For parsing simply split on the space ' '. However if you have more complex expressions consider a post order traversal, or stack implementation.
This question has already been answered here: Evaluating a math expression given in string form
I gave a very simple breakdown in my answer here as well: Calculating String-inputed numerical expressions?
You can use the StringTokenizer to split the string wherever it finds a space.
String s = "3 5 *";
StringTokenizer st = new StringTokenizer(s);
You can check if there are more tokens via st.hasMoreTokens().
You can use the token aka string via st.nextToken() (it returns a string).
You can also cast each "string" such as the "3" into a double via:
String firstNumString = "3";
Double first = Double.parseDouble(firstNumString);
This results in the Double variable 'first' containing the number 3.
Related
I want to make a Java program in which I want to take a String as a input. The string will have two integer numbers and operation to be performed.
eg. 25+85
or 15*78
The output will the solution of the string.
But I don't know how to split the string because operator sign is not known before execution.
You would want to check what operation it is using by using String.contains("+"); and checking all the other operators you want to support. Then split wherever that operator is, String.split("+"). From there parse the output of String.split("+") by using Integer.parseInt(String s) and then return the sum. Pretty simple, good luck.
You can use the split() method of the String class to split the input at non-digit characters:
input.split("\\D");
This will give you an array containing only the numbers.
I guess you also want to get the operator somehow? Although it's not the most elegant way, you might want to start with input.replaceAll("[^\\*\\+\\-\\/]", "") to remove everything that's not an operator, but you will still have to do some careful input filtering. What if i type 5+4*6 oder 2+hello ?
I'm working on a piece of code where I've to split a string into individual parts. The basic logic flow of my code is, the numbers below on the LHS, i.e 1, 2 and 3 are ids of an object. Once I split them, I'd use these ids, get the respective value and replace the ids in the below String with its respective values. The string that I have is as follow -
String str = "(1+2+3)>100";
I've used the following code for splitting the string -
String[] arraySplit = str.split("\\>|\\<|\\=");
String[] finalArray = arraySplit[0].split("\\(|\\)|\\+|\\-|\\*");
Now the arrays that I get are as such -
arraySplit = [(1+2+3), >100];
finalArray = [, 1, 2, 3];
So, after the string is split, I'd replace the string with the values, i.e the string would now be, (20+45+50)>100 where 20, 45 and 50 are the respective values. (this string would then be used in SpEL to evaluate the formula)
I'm almost there, just that I'm getting an empty element at the first position. Is there a way to not get the empty element in the second array, i.e finalArray? Doing some research on this, I'm guessing it is splitting the string (1+2+3) and taking an empty element as a part of the string.
If this is the thing, then is there any other method apart from String.split() that would give me the same result?
Edit -
Here, (1+2+3)>100 is just an example. The round braces are part of a formula, and the string could also be as ((1+2+3)*(5-2))>100.
Edit 2 -
After splitting this String and doing some code over it, I'm goind to use this string in SpEL. So if there's a better solution by directly using SpEL then also it would be great.
Also, currently I'm using the syntax of the formula as such - (1+2+3) * 4>100 but if there's a way out by changing the formula syntax a bit then that would also be helpful, e.g replacing the formula by - ({#1}+{#2}+{#3}) *
{#4}>100, in this case I'd get the variable using {# as the variable and get the numbers.
I hope this part is clear.
Edit 3 -
Just in case, SpEL is also there in my project although I don't have much idea on it, so if there's a better solution using SpEL then its more than welcome. The basic logic of the question is written at the starting of the question in bold.
If you take a look at the split(String regex, int limit)(emphasis is mine):
When there is a positive-width match at the beginning of this string then an empty leading substring is included at the beginning of the resulting array.
Thus, you can specify 0 as limit param:
If n is zero then the pattern will be applied as many times as possible, the array can have any length, and trailing empty strings will be discarded.
If you keep things really simple, you may be able to get away with using a combination of regular expressions and string operations like split and replace.
However, it looks to me like you'd be better off writing a simple parser using ANTLR.
Take a look at Parsing an arithmetic expression and building a tree from it in Java and https://theantlrguy.atlassian.net/wiki/display/ANTLR3/Five+minute+introduction+to+ANTLR+3
Edit: I haven't used ANTLR in a while - it's now up to version 4, and there may be some significant differences, so make sure that you check the documentation for that version.
I'm having trouble fully understanding arrays. I understand what a int array is, a set of numbers grouped together with their own locations, but I don't understand the purpose of string arrays vs strings, or how to get the user to input a string.
So, I have to make it so that the user enters a string with a % somewhere, and then another string, where the % is, the second string they enter needs to go there. I am NOT looking for a copy paste thing, but an explanation on what code I should use an what it does for that action.
You need a java.util.Scanner
You would enter a String containing a % character
Then, you String#replace that value with a second input string.
No arrays necessary...
I'm making a calculator, and some computations require 3 pieces of information (eg, 3*4), whereas other only require 2 (eg, 5!).
I have managed to split the input into 3 parts using the following code:
String[] parts = myInput.split(" ");
String num1 = parts[0];
String operation = parts[1];
String num2 = parts[2];
But this means that when I only type 2 things, it doesn't work.
How can I allow for either 3 or 2 things as an input?
You should not assume that the input will always in the 3 parameter form. Rather, take a generic input, parse on it based on use cases.
In your case, it boils down to two specific use cases AFTER you accept the input:
Operators that operate on single operand - unary operator
Operators that operate on double operand - binary operator
For each case, you can define a list of operators allowed. E.g. '!' will be in case 1 list, while '*' will be in case '2'
scan through the string, look for the operator position. [^0-9] (represents a pattern which other than numbers). Or simply you can do a trivial check for the operator (by creating your own custom method)
Once you have figured out this, validate your string (optional) - e.g. makes no sense to have two operands for a unary operator.
Having done this, it is fairly easy to parse now the required operands by splitting out the string based on the operator. Computation is fairly trivial then.
Hope this helps.
Without knowing more I can't help you find a better design to accommodate for the commonalities and variances. But to answer the stated questions....
You can use parts.length to know many variables you were given and use that to branch your code (i.e. if else statement).
I'm very new to the world of Java programming, and although I know this is a ridiculously easy question, I can't seem to phrase my searches in a way that turns up the answer I need...so hopefully someone from this community won't mind helping me.
MY program needs to take an input line from a .csv file and split it into fields of an array, using commas as delimiters. The fields of the array are then assigned to variables that are different data types - char, int, float, and string. What I'm struggling with is the formatting for my String variables.
Here is part of my code:
public void parseCSV(String inputLine) {
String[] splitFields;
splitFields = inputLine.split(",");
try {
empNumber = Integer.parseInt(splitFIelds[0[);
payType = splitFields[1].charAt(0);
hourlyRate = Float.parseFloat(splitFields[2]);
last name =
I need to assign variable lastName, a String data type, to position 3 of my splitFields array. I just don't know how to format it. Help would be greatly appreciated!
A warning on your overall approach
Go with the other answers if you're doing a homework assignment with a simple csv file, but splitting a String on the comma character , will not work for more complicated CSVs. Example:
"Roberts, John", Chicago
This should be read as two cells where the first string is Roberts, John. Naive splitting on , will read this as three cells: "Roberts, John", and Chicago.
What you should be doing (for robust code)
If you're writing serious/production level code, you should use the Apache Commons CSV library to parse CSVs. There are enough tricky issues with commas and quotations, enough variation in possible formats that it makes sense to use a mature library. There's no reason to reinvent the wheel.
Another tool for parsing text
If you're a beginner, this might be opening up a can of worms, but a powerful tool for parsing/validating text input is "regular expressions." Regular expressions can be used to match a string against a pattern and to extract portions of a string. Once you have extracted a String from a specific cell of a csv, you could use a regular expression to validate that the String is in the format you're expecting.
While you're unlikely to really need regular expressions for this project, I thought I'd mention it.
String.split(...) returns a String[] so you really can just assign a specific index to a String.
String s = "one two dog!";
String[] sa = s.split(" ");
String ns = sa[1]; // ns now equals "two"
so you can just:
last_name = splitFields[index]; // this will work fine as long as index is within the `array` bounds.
Please mind that your last name var has a space(that might have been you problem).
I also recommend minding the parses, Integer.parseInt(...) & Float.parseFloat(...) might throw a NumberFormatException if you try to parse a non decimal values.
Easy, it is already a String, so you do not have to perform additional parsing. The following assignment will do the trick:
lastName = splitFields[3];