Illegal start of expression java operators - java

I am trying to write a program that evaluates a postfix expression. My idea is to stack the operands and then pop out the necessary operands when an operator occurs. I am trying to check if the input is an operand is an operator or operand, but the only "if" statement of this beginning code is returning "error: illegal start of expression" at the first instance of ||. Am I missing escape characters or something else? Thanks in advance.
public class Evaluate{
char input[] = new char[50];
Stack operands = new Stack();
public string Evaulate(string input){
for (int k = 0; input[k] != null; k++){
char symb = input.charAt[k];
if (symb != (+ || - || * || / || $){
operands.push(symb);
}
}
}
}

For a start, conditions don't quite work that way:
if (symb != (+ || - || * || / || $) ...
What you should be doing is first comparing them with characters rather than "naked" Java tokens (or $).
You should also be doing full comparisons between each || or, since you're using negative logic here to detect non-operators, &&:
if ((symb != '+') && (symb != '-') && ...
There are a few other problems in your code which I haven't mentioned but that should fix your immediate problem.

The expression
symb != (+ || - || * || / || $
is not valid in Java. Even after closing the parentheses and quoting the symbols, like this:
symb != ('+' || '-' || '*' || '/' || '$')
it is still not valid. You may want it to mean something that it does not, based on the way we can use "or" in English (i.e., "symbol is not a plus or a minus or a star or a slash or a dollar sign"). But Java just doesn't do things that way.
Fortunately there is a better way to determine whether a character (in this case symb) is one of a certain set of characters:
if ("+-*/$".indexOf(symb) >= 0) {
This computes the position of symb within the string "+-*/$" which, if symb is one of the desired characters, will be 0, 1, 2, 3, 4, or 5. If it is not, the expression returns -1. So the >=0 check serves as the membership check you are looking for.

Related

java password checker with special characters

I'm very new to Java so please bear with me.
My assignment:
Ask the user to input a password and write a message stating whether or not it is acceptable. The password requirements:
the password is at least 8 characters long
it has upper case and lower case letters
at least one letter is followed by a number
it has one of the special characters $#?!_-=%
I really dont now what to do on number 3 and 4. Ive read something about regex but we didnt even had that in class. are there any other possible methods?
For number 3 you can use the cycle. Inside it, you can catch every letter via isLetter() method and then check the following element of your array by isDigit() method
boolean isLetterFollowedByNumber;
for (int[] a : nameOfYourArray) {
if (Character.isLetter(array[i]) && Character.isLetter(array[i])) {
isLetterFollowedByNumber = true;
}
}
For number 4 you can just compare every element of your array of char with special characters
boolean hasCharacter;
for (int[] a : nameOfYourArray) {
if (a == '$' || a == '#' || a == '?' || a == '!' || a == '_'- || a == '=' || a == '%') {
hasCharacter = true;
}
}
Both of my examples include for-each loop, but you can use for loop as well. Good luck with your task!

Is there a cleaner way of doing this if statement?

if(input.charAt(i) == '0' || input.charAt(i) == '1' || input.charAt(i) == '2') {
}
Is there a way to condense this if condition, or no?
You could check if the character matches any index in a common String. Like,
if ("012".indexOf(input.charAt(i)) > -1) {
}
Maybe a little more readable (in java 9+)
if (Set.of('0', '1', '2').contains(input.charAt(i))) {
}
You can make it shorter by assigning the character lookup result in a variable (but still three equality checks).
char c = input.charAt(i);
if(c == '0' || c == '1' || c == '2') {
}
You can look at the other answers like creating a Set/Array and doing the contains check if the number of equality checks will increase in the future. IMO, three checks should be fine to be written as is.

Which is an efficient way to check if a character is alphabetic or not?

What could be an efficient way to check a character is alphabet or not?
Using
Character.isLetter(ch)
(or)
if( (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))
Checking for A-Z a-z does not check all alphabetic characters. so the question seems moot.
Character.isAlphabetic(c) tests whether c is alphabetic.
Character.isLetter(c) tests whether c is a letter.
The two are not equivalent so you should be clear on the question you're trying to answer. The difference is that there are number-indications that are alphabetic but not letters; think Roman numerals. Link to list.
//function to check whether given character is an alphabet or not
function check(n){
var a=(+n); //If unary operator operates on a string then we get NaN.
if(isNaN(a)){ //Checking if a is NaN
console.log("This is a alphabet")
}
else{
console.log("Is a number")
}
}
check(12)
check("a");

Methods of comparing strings in java and why this code returns with an error

Right now, I have the code written that is displayed below:
if(letterTwo.equals("a" || "e" || "i" || "o" || "u") && !"a" || "e" || "i" || "o" || "u".equals(letterOne));{}
The errors I am receiving are:
"The operator ! is undefined for the argument types string", and "The operator || is undefined for the argument types string, java.lang,string, java.lang.string"
I was wondering how I could fix this code, and what the operators are used for comparing strings like I need to.
Assumption: letterTwo is a String
letterTwo.equals() expects a single String argument. Not the big boolean expression you are passing it.
You can either do
if (letterTwo.equals("a") || letterTwo.equals("b") || letterTwo.equals("c"))
{
//etc
}
Or if your Java version is new enough you may be able to use a switch
switch(letterTwo)
{
case "a":
case "b":
case "c": // stuff
break;
}
If letterTwo is actually a char (which it may well be given the name...), you can do similar things but it is a bit easier:
if (letterTwo == 'a' || letterTwo == 'b' || letterTwo == 'c')
{
//etc
}
Simple:
if (letter.equals("a") || letter.equals("b")
And so on. The point is that you have to use those boolean operators on expressions that have type boolean!
But of course, code as the above turns unreadable quickly. In the real world, such kind of checks would rather be done using a simple regular expression.
The correct way for you would be :
if( (letterTwo.equals("a") || letterTwo.equals("e") || letterTwo.equals("i") || letterTwo.equals("o") || letterTwo.equals("u")) && !(letterOne.equals("a") || letterOne.equals("e") || letterOne.equals("i") ||letterOne.equals("o") || letterOne.equals("u")) ;{}
Please note, this is not case-sensitive. It would treat "A" and "a" differently.If you want them to be treated in same way use "equalsIgnoreCase" instead of "equals" above.
As pointed out by #GhostCat above, it distrubs readability and regex should be much better to handle such cases

Writing one regular expression for string in java

I am trying to write one regular expression for string. Let us say there is a string RBY_YBR where _ represents empty so we can recursively replace the alphabets and _ and the result is RRBBYY_ . There can be two or more alphabet pairs can be formed or something like this also RRR .
Conditions
1). Left or right alphabet should be the same.
2). If there is no _ then the alphabet should be like RRBBYY not RBRBYY or RBYRBY etc.
3). There can be more than one underscore _ .
From regular expression I am trying to find whether the given string can satisfy the regular expression or not by replacing the character with _ to form a pattern of consecutive alphabets
The regular expression which I wrote is
String regEx = "[A-ZA-Z_]";
But this regular expression is failing for RBRB. since there is no empty space to replace the characters and RBRB is also not in a pattern.
How could I write the effective regular expression to solve this.
Ok, as I understand it, a matching string shall either consist only of same characters being grouped together, or must contain at least one underscore.
So, RRRBBR would be invalid, while RRRRBB, RRRBBR_, and RRRBB_R_ would all be valid.
After comment of question creator, additional condition: Every character must occur 0 or 2 or more times.
As far as I know, this is not possible with Regular Expressions, as Regular Expressions are finite-state machines without "storage". You would have to "store" each character found in the string to check that it won't appear later again.
I would suggest a very simple method for verifying such strings:
public static boolean matchesMyPattern(String s) {
boolean withUnderscore = s.contains("_");
int[] found = new int[26];
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if (ch != '_' && (ch < 'A' || ch > 'Z')) {
return false;
}
if (ch != '_' && i > 0 && s.charAt(i - 1) != ch && found[ch - 'A'] > 0
&& !withUnderscore) {
return false;
}
if (ch != '_') {
found[ch - 'A']++;
}
}
for (int i = 0; i < found.length; i++) {
if (found[i] == 1) {
return false;
}
}
return true;
}
Please take my answer with a grain of salt, since it's a bit of a "Fastest gun in the West" post.
It follows the same assumptions as Florian Albrecht's answer. (thanks)
I believe that this will solve your problem:
(([A-Za-z])(\2|_)+)+
https://regex101.com/r/7TfSVc/1
It works by using the second capturing group and ensuring that more of it follow, or there are underscores.
Known bug: it does not work if an underscore starts a string.
EDIT
This one is better, though I forgot what I was doing by the end of it.
(([A-Za-z_])(\2|_)+|_+[A-Za-z]_*)+
https://regex101.com/r/7TfSVc/4

Categories

Resources