Need help splitting input from a String into int - java

I have the user input a fraction problem in this format (4/8–3/12 or 3+2/3 or 12/16*4 or -2/3/64/96) and need to split up the two fractions into an array then I need to pull the numerator and denominator of both so I can simplify them in my other file and do whatever calculation it asks, so I need to use an array so i can call on the element that has the sign in it.
System.out.println("Enter Fraction:");
String answer = s.nextLine();
String[] numbers = answer.split(" ");
System.out.print(numbers);
Is there a way to split the array into int variables? I am lost. The solution might be simple but been at this project for 7 hours or so now.

You can split the input with a simple regular expression, like this:
Pattern p = Pattern.compile("\\d+|[+-/*]");
String inp = "2/3/64/96";
Matcher m = p.matcher(inp);
while (m.find()) {
System.out.println(m.group());
}
The heart of this solution is a regular expression:
\\d+|[+-/*]
\\d+ means "one or more digit; [+-/*] means "any of the +, -, /, or *".
Here is a demo on ideone.
Note that your program would need to be really careful about deciding if a + or a - is a unary "change sign" or a binary operation: when the sign is at the beginning or just after another operator, it's unary; otherwise, it's binary.

Eric Lippert has the best advice I've seen when dealing with these problems.
Write the problem out in english/pseudo code then start changing the pseudo code to real code.
Get Answer from user
Break Answer up to the 2 fractions/numbers and the math operator
Take the 2 different fractions and convert them to a double, float, whatever you need
Apply the math operation to the 2 numbers from the above step
Output the answer
Now just start replacing each line with how you would do that. I feel confident that you can probably figure out each step, but sometimes we get lost when thinking of the problem as a whole. If you can't figure out an individual step, post the code you have tried and we can help with a specific problem.

Your code so far just splits input into expressions. Your still need to split expressions into fractions.
When you already have String array of fractions you can split each element into 2 integers:
Split it into sub-strings with split("/")
Convert each sub-string to int with Integer.parseInt() method.

Related

java String.replaceAll char between two numbers

I would like to replace all char '-' that between two numbers, or that between number and '.' by char '&'.For example
String input= "2.1(-7-11.3)-12.1*-2.3-.11"
String output= "2.1(-7&11.3)-12.1*-2.3&.11"
I have something like this, but I try to do it easier.
public void preperString(String input) {
input=input.replaceAll(" ","");
input=input.replaceAll(",",".");
input=input.replaceAll("-","&");
input=input.replaceAll("\\(&","\\(-");
input=input.replaceAll("\\[&","\\[-");
input=input.replaceAll("\\+&","\\+-");
input=input.replaceAll("\\*&","\\*-");
input=input.replaceAll("/&","/-");
input=input.replaceAll("\\^&","\\^-");
input=input.replaceAll("&&","&-");
input=input.replaceFirst("^&","-");
for (String s :input.split("[^.\\-\\d]")) {
if (!s.equals(""))
numbers.add(Double.parseDouble(s));
}
You can make it in one shot using groups of regex to solve your problem, you can use this :
String input = "2.1(-7-11.3)-12.1*-2.3-.11";
input = input.replaceAll("([\\d.])-([\\d.])", "$1&$2");
Output
2.1(-7&11.3)-12.1*-2.3&.11
([\\d.])-([\\d.])
// ^------------replace the hyphen(-) that it between
// ^__________^--------two number(\d)
// ^_^______^_^------or between number(\d) and dot(.)
regex demo
Let me guess. You don't really have a use for & here; you're just trying to replace certain minus signs with & so that they won't interfere with the split that you're trying to use to find all the numbers (so that the split doesn't return "-7-11" as one of the array elements, in your original example). Is that correct?
If my guess is right, then the correct answer is: don't use split. It is the wrong tool for the job. The purpose of split is to split up a string by looking for delimiter patterns (such as a sequence of whitespace or a comma); but where the format of the elements between the delimiters doesn't much matter. In your case, though, you are looking for elements of a particular numeric format (it might start with -, and otherwise will have at least one digit and at most one period; I don't know what your exact requirements are). In this case, instead of split, the right way to do this is to create a regular expression for the pattern you want your numbers to have, and then use m.find in a loop (where m is a Matcher) to get all your numbers.
If you need to treat some - characters differently (e.g. in -7-11, where you want the second - to be an operator and not part of -11), then you can make special checks for that in your loop, and skip over the - signs that you know you want to treat as operators.
It's simpler, readers will understand what you're trying to do, and it's less error-prone because all you have to do is make sure your pattern for expressing numbers accurately reflects what you're looking for.
It's common for newer Java programmers to think regexes and split are magic tools that can solve everything. But often the result ends up being too complex (code uses overly complicated regexes, or relies on trickery like having to replace characters with & temporarily). I cannot look at your original code and convince myself that it works right. It's not worth it.
You can use lookahead and lookbehind to match digit or dot:
input.replaceAll("(?<=[\\d\\.])-(?=[\\d\\.])","&")
Have a look on this fiddle.

I need a regex command that isolates all numbers not adjacent to a caret (^)

I am having a lot of trouble figuring Regex command out, and can't seem to find the right combination to fit what I want
Example:
Input: 1x^3+5x^2+6x+2
Output: 1 5 6 2
I need to isolate those values, as they are the coefficients of my polynomial. The input is a String so I figured the best way to do this was by using the .split() function with a custom Regex command.
You can use this regular expression:
(?<!\^)\d+(?!\^)
This uses a negative lookahead and lookbehind to remove characters next to ^.
Since you want to extract coefficients, it finds one or more digits. Modified the middle part if needed.
You can use it this way in Java, for example:
Matcher m = Pattern.compile("(?<!\\^)\\d+(?!\\^)").matcher("1x^3+5x^2+6x+2");
while (m.find()) {
System.out.println("Coefficient: " + m.group());
}
EDIT:
If you also want to detect negative coefficients, you can check for an optional - before digits:
(?<!\^)-?\d+(?!\^)
Keep in mind that as you try to capture more complicated patterns, regular expressions become less suitable as you may get lost in a number of cases to cover.

Regular Expression does not accept correct inputs

I am developing a Java method, which checks, if the user input is valid. For that I wrote four regular expressions to check that. The first three work fine. The last one, the "most complex" regular expression, does not accept values, which should be accepted.
I want to make sure, that the user entered one of three different input settings.
One to six "L" followed by a number from 1-16
One to six "R" followed by a number from 1-16
One B followed by a number from 1-16
My problem is to define, that only numbers from 1-16 will be accepted. My regular expression is accepting 1-9, but not any number above 9.
Let's take the "B"-case for example, than this is my regular expression:
String regexB = "B[([1-9]{1})((1[0-6]){1})]";
What I tried to do with my expression:
One "B", followed by one single number from 1-9 OR by a "1" and a second single number from 0-6.
I know, that this is possibly not a hard question, but maybe one of you guys is able to save me from losing some time by trying to solve this.
Thanking you in anticipation.
String regexB = "B([1][0-6]|[1-9])";
B
a digit 1 and 0-6 OR
a digit between 1 and 9
I think your regexp is invalid.
Try the following (for B example)
B((1{1}[0-6]{1})|([1-9]{1}))
String regexB = "B([1-9]|([1][0-6]))";
edit: oh ... the answer is already there ...
Here is a tool that will help you: http://utilitymill.com/utility/Regex_For_Range.
In your case: [1-9]|1[0-6]

Regular Expression for numbers with chance of having the decimal

Guys I just started learning Regular Expression in java. I am trying to construct a regular expression for a number. It is ok for integers if I use "\d+".
But if there is any decimal number, it is obvious that the above RE won't work.
So I constructed a RE that is "\d+\.\d+" . It is ok for decimal numbers but
NOT FOR INTEGERS.
So I want to make a RE for BOTH INTEGERS and DECIMALS. Any idea is appreciated.
Make the part after the decimal point optional.
"\d+(?:\.\d+)?"
The leading ?: after the initial parenthesis is just to avoid creating a matching group.
You can try to use this regex:
/^\d*\.?\d*$/
The Javadoc for java.lang.Double#valueOf(String) gives a detailed but well-documented regular expression for how it parses numbers. You may find it instructive to read that and work out which parts are relevant to your problem.

Checking on 3 criteria

i am trying to check on 3 condition to validate a car plate number. But i just cant seems to check all 3 conditions. length must be between 4 -7. first 3 char must be from a - z. fourth char onwards must be digits '0' - '9'.
I have problem on the next part of my question. i need to implement compute CheckDigit method which i have tried to add in an array to accept the arguement for me to do the step by step instruction to compute the check digits.
Below is the steps,
take 2nd & 3rd char and convert is to numbers that correspond to the alphabet. eg. A is 1 B is 2.
add 0 to the front of the numbers is the numbers has less den 4 digits. eg. SBA123 need to append to 0123
multiply each digits in step 1 and 2 by 14,2,12,2,11,1
sum up number from step 3
divide sum in step 4 by 19 and take remainder and find the check digit in a table.
Any help will be great for me to start.
below is my code i have change,
Kindly point out my mistake.
public static void validateCarPlate(String y)throws InvalidCarPlateException{
String rex = "[a-zA-Z]{3}[0-9]{1,4}";
if(y.matches(rex)){
computeCheckDigit(y);
}else{
throw new InvalidCarPlateException();
}
}
public static void computeCheckDigit(String x){
int [] arr = Integer.parseInt(x);
}
The use of Regular Expressions would be ideal here. Regular Expressions are funny looking, well constructed strings that represent a Finite State Machine that recognizes certain types of strings as matching a pattern or not matching. Learning about regular expressions will greatly improve your string matching/validation processes.
This is the RegEx you should use: ^[a-zA-Z]{3}[0-9]{1,4}$
Lets break down what this funny looking string means:
^ : This is the start of the string (no characters before it)
[a-zA-Z] : Alphabetic characters
{3} : Exactly 3 of these alphabetic characters
[0-9] : Then numeric characters
{1,4} : Between 1 and 4 of these numeric characters (inclusively)
$ : This is the end of the string (no characters remaining)
An example usage:
String myStr = "abc123";
System.out.println(isValidString(myStr));
public boolean isValidString(String input) {
String regex = "^[a-zA-Z]{3}[0-9]{1,4}$";
if(input==null) { return false; }
return input.trim().matches(regex);
}
You can do this using regex very easily, the expression
^[a-z]{3}[0-9]{1,4}$
Would work.
Here is an example
public boolean validatePlate(final String string) {
final Matcher matcher = Pattern.compile("^[a-z]{3}[0-9]{1,4}$").matcher(string);
return matcher.matches();
}
You are always testing the first character of your string (charAt(0)) instead of using the value of the loop counter i that you set up. Also, you have no test for the digits.
You could also look into "String.indexOf()"; it would save you having to loop through (or initialize) an array of chars. Have a string "abcdefg..." (and another "01234...").
You could also look into the methods Character.isLetter() and Character.isDigit() and do away with the arrays and the strings-treated-like-arrays.
As for regular expressions, I always like the old joke: "Say you have a problem, and you decide to solve it with regular expressions. Now you have two problems..." Of course they're useful, but not nearly as much as many people seem to think they are. And not everything that CAN be solved with them SHOULD be solved with them. If you're interested, this is a nice simple regular expression problem to get started with. If you're not, don't feel like your solution is lacking somehow.

Categories