Valid Parentheses Java - java

I am trying to solve the Valid Parentheses problem in Java (described here among other places: Valid Parentheses)
My code is as follows thus far:
class Solution {
public boolean isValid(String s) {
if(s.charAt(0) ="(") {
if(s.charAt(s.length-1) != ")"){
system.out.println("false");
}
}
if(s.charAt(0) ="[") {
if(s.charAt(s.length-1) != "]"){
system.out.println("false");
}
}
if(s.charAt(0) ="{") {
if(s.charAt(s.length-1) != "}"){
system.out.println("false");
}
}
}
}
Currently I am getting the following error:
Line 4: error: unexpected type
if(s.charAt(0) ="("){
Can anyone advise on what the issue is? I can't at the moment figure it out but feel like it's something simple I'm overlooking.

Two immediate issues:
Character values are single-quoted in Java, e.g. char c = 'c';
Primitive comparison is done with ==. The single equals sign = is used for assignment.
So that line should be:
if(s.charAt(0) == '(') { /* ... */ }
Note that this only fixes the most immediate error you're experiencing. After fixing that, there are some more, for example system.out.println() should be System.out.println().
And, after fixing that, I think you're still a way off from solving the actual assignment. Just keep at it & good luck!

There are some issues in your answer. Robby Cornelissen points you out some issues in his answer. And I also saw 2 errors in your code.
s.length should be s.length().
You don't have a return statement in the isValid method.
Issue 1
In the following statement, you are missing the brackets () after the length. Length is a method in Java that is used to get the length of a Java String that you know already.
if(s.charAt(s.length - 1) != ')')
So your above statement should be as follows.
if(s.charAt(s.length() - 1) != ')')
Issue 2
In your isValid method it's returning a boolean value. The return type of that method is boolean. But you are not returning any boolean value inside your method. So you have to add a return statement. It may be,
return true; or return false; or any boolean variable declared inside isValid method.

it is best to use stack for valid parentheses in Java
class Solution {
public boolean isValid(String s) {
Stack stack = new Stack();
for(int i=0; i<s.length; i++){
if(s[i] =='('){
stack.push(')')
}
else if(s[i] == '['){
stack.push(']')
}
else if(s[i] =='{'){
stack.push('}')
}
else if(s[i] !== stack.pop()){
return false;
}
}
return true;
}
}

Related

How to return an error in a Boolean method?

I have a method that returns True or False depending on the input being either 'y' or 'n'. However I want it to return an error when anything else is entered to the question asked. I'm asking how to return a String for example in a Boolean Method. Here is what I have so far:
public static boolean askYesNo(String question1) {
question = question1;
System.out.println(question);
answer = kbdScanner.next();
if (answer.charAt(0) == 'y') {
return true;
}
else if (answer.charAt(0) == 'n') {
return false;
}
return ?????;
}
Thanks
A method in Java can always only have one return type. In your case that is boolean, so you cannot return a String.
What you require is an Exception. Exceptions can be thrown e.g. if something unexpected happens. Read more about it here: http://beginnersbook.com/2013/04/java-exception-handling/
In your case, I suggest using an IllegalArgumentException since you want to handle the case that the method input is not valid.
a possible solution is to validate the answer before calling the method.
So in abstract code:
while (answer is not y or n) {
ask question again
}
call method
Just do
throw new IllegalArgumentException(question1);

Do I have this written properly? .equals AND !.equals if statement

FIXED. To get the statement to evaluate the way I wanted it to I had to write it this way:
public static Boolean pushCard(String S1, String S2) {
Boolean result = false;
if ((S1.equals("fire") || S1.equals("wind") || S1.equals("water")))
if (!S2.equals("fire") && (!S2.equals("water") && (!S2.equals("fire"))))
result = true;
return result;
} //end push card method
I can not tell if this comparison is causing issues. I was using == instead of .equals but then I learned that it was the wrong way to write it. Thanks for the help!
public static Boolean pushCard(String S1, String S2) {
Boolean result = false;
if ((S1.equals("fire") || S1.equals("wind") || S1.equals("water")))
if (!S2.equals("fire") || (!S2.equals("water") || (!S2.equals("fire"))))
result = true;
return result;
} //end push card method
Syntactically, your code will compile just fine, and the way you use .equals() method to compare strings is correct. Your use of the ! operator is also correct.
There is no guarantee that your code will not have logical errors though.
The only problem I can see you have "fire" mentioned twice in your second if statement. Otherwise, any problems you might be having could be related to your logic being wrong, since your syntax is pretty much correct and your usage is proper.
It is unclear what you're asking. The second if will always be true. You probably need :
if ((S1.equals("fire") || S1.equals("wind") || S1.equals("water")))
if (!S2.equals("fire") && (!S2.equals("water") && (!S2.equals("wind"))))
result = true;
public static Boolean pushCard(String S1, String S2)
{
Boolean result = false;
if (S1.equals("fire") || S1.equals("wind") || S1.equals("water"))
{
(!S2.equals("fire") || !S2.equals("water"))
result = true;
}
return result;
}
/end push card method
you had an extra pair of brackets in the first if statement.
I believe an if statement needs brackets {} when the code inside it is larger than one line.
your second if statement can be altered to just !S2.equals("fire") || !S2.equals("water")

Error with return in Java?

I get an error in the code from this part of my code:
public boolean findCustomer(String inPersonalNumber){
// check if personal number already exist
for (int i=0; i<customerList.size();i++) {
if(customerList.get(i).getCustomerPersonalNumber().equals(inPersonalNumber)){
return true;
}
}
return true;
}
When I remove the first return true and instead to the last return true, it don't get the error in my eclipse code, but why can't I have the first place and would this be the same? Thanks!
EDIT: The error message from eclipse say: This method must return a result of type boolean. I'm confused because isn't that what I have done?!
Yes, a break must be in the code
Can I write the method in some other way?
EDIT NUMBER 2
Why isn't this code working?
public boolean findCustomer(String inPersonalNumber){
// check if personal number already exist
for (int i=0; i<customerList.size();i++) {
if(customerList.get(i).getCustomerPersonalNumber().equals(inPersonalNumber)){
return true;
}
else {
return false;
}
}
}
This method returns a boolean value so I don't understand why I get an error!? The code looks right to me?
Your edit #2 doesn't compile because there is a possibility that your code won't enter the for-loop. This will be the case if customerList.size() is 0. To fix this, you'll simply need to add a return statement after the for-loop as well:
// check if personal number already exist
for (int i=0; i<customerList.size();i++) {
if(customerList.get(i).getCustomerPersonalNumber().equals(inPersonalNumber)){
return true;
}
else {
return false;
}
}
return false;
Another point here is that this code doesn't logically make much sense: it will only return true or false based on the first item in your list. And this is probably not what you want. So take a closer look at several of the other answer here, many of which are good examples for how you can do this.
public boolean findCustomer(String inPersonalNumber){
boolean result = false;
// check if personal number already exist
for (int i=0; i<customerList.size();i++) {
if(customerList.get(i).getCustomerPersonalNumber().equals(inPersonalNumber)){
result = true;
break;
}
}
return result ;
}
When I remove the first return true and instead to the last return
true, it don't get the error in my eclipse code, but why can't I have
the first place and would this be the same?
If you remove the second return statement the code would be able to run and not return a value - this is not possible as you defined the method to have a return type of Boolean. So it must always return a value no matter what.
Just change the second return statement to false, should do what you want.
Looks like you have turned off the Build Automatically feature of eclipse. It maybe complaining about an error that used to be present when you still hadn't typed in your code fully! This can also happen if you have back-dated your system for some reason.
Also, shouldn't you be returning false if the condition doesn't satisfy?
public boolean findCustomer(String inPersonalNumber) {
// check if personal number already exist
for (int i = 0; i < customerList.size(); i++) {
if (customerList.get(i).getCustomerPersonalNumber().equals(inPersonalNumber)) {
return true;
}
}
return false;
}
First return will return only in case of all conditions satisfied, but this method should be returning boolean as per code. It would be expecting a return in failure case also.
Removing first return won't affect compilation as it has a return in second place which will work without any condtions.
Edit : Answer for your second question
This code has two return's, but what if your customerList is size 0, in that case also, method must return boolean. right? for that only, compiler is asking.
BTW, code doesn't have null checks.
Your final code could be this. Keeping multiple return statements in code in not a good practice.
public boolean findCustomer(String inPersonalNumber) {
boolean retVal = false;
if (!(inPersonalNumber == null || inPersonalNumber.trim().equals("")
|| customerList == null || customerList.size() == 0)) { // inputs are valid to run this check
// check if personal number already exist
for (int i = 0; i < customerList.size(); i++) {
if (inPersonalNumber.equals(customerList.get(i).getCustomerPersonalNumber()) { // to avoid NPE, kept inPersonalNumber in check
retVal = true;
break;
}
}
}
return retVal;
}
Because your for loop looses meaning if you're returning true anyway.
If you want to stop loop use break; instead of first return.

playing with java Operators (XOR and AND/OR)

In a program I am trying to check two boolean values (returned from a function); the condition that needs to be checked is:
- only if any one of the returned value is true and the other is false then I have a problem;
- else if both are true or false I am good to go to next step.
Which of the following two examples would be the efficient way to check the condition, or is there a better solution?
a and b are integer values on which I am checking a condition for correctness in isCorrect function and it return true or false.
1.
// checking for the correctness of both a and b
if ((isCorrect(a) && !isCorrect(b)) ||
(!isCorrect(a) && isCorrect(b)))
{
// a OR b is incorrect
}
else
{
// a AND b are both correct or incorrect
}
2.
// checking for the correctness of both a and b
if (! (isCorrect(a) ^ isCorrect(b)))
{
// a OR b is incorrect
}
else
{
// a AND b are correct or incorrect
}
Thanks,
Ivar
P.S: code readability is not an issue.
EDIT: I meant to have an XOR in the second option.
Also, I agree with the == and != options, but what if I had to use boolean operators?
if (isCorrect(a) != isCorrect(b)) {
// a OR b is incorrect
} else {
// a AND b are correct or incorrect
}
Your test doesn't need boolean operators, just this:
if (isCorrect(a) == isCorrect(b)) {
// they both have the same value
} else {
// they don't ...
}
EDIT - I deliberately didn't use the same comments to reflect that the primary purpose of the comment should be to describe the intent, and not the specific implementation. In this case the simplest statement of intent is that both a and b obtained the same result.
simply:
if (isCorrect(a) == isCorrect(b))
{
// a AND b are both correct or incorrect
} else {
// a OR b is incorrect
}
How about this?
if(isCorrect(a) != isCorrect(b))
{
//problem
}
else
{
//not a problem
}
You can use XOR also, but != works fine and is more readable if you are dealing with boolean values, IMO.

Why is false being returned in this function

In my program below, I set the variable th as true in the second if statement.
I'm curious why it later returns as false.
public boolean nodeExist(TreeNode Tree, T value){
boolean th = false;
if(Tree.getValue()!= null){
if(value == Tree.getValue()){
th = true;
}else{
if(value.compareTo((T) Tree.getValue()) < 0){
nodeExist(Tree.getLeft(), value);
}else{
nodeExist(Tree.getRight(), value);
}
}
}else{
th = false;
}
return th;
}
You probably look at a recursive call which sets th to true. But when that call returns to its caller, that th is still at false, and that's then returned. You need to assign the recursive callee's result:
if(value.compareTo((T) Tree.getValue()) < 0){
th = nodeExist(Tree.getLeft(), value);
}else{
th = nodeExist(Tree.getRight(), value);
}
You already got your answer. In future, to prevent mistakes like this, it's better to just return the value right away if you can. IT'S OKAY to have multiple return; if used properly, it can read to more readable code.
public boolean nodeExist(TreeNode Tree, T value){
if (Tree.getValue() == null) return false;
if (value == Tree.getValue()) return true;
if (value.compareTo((T) Tree.getValue()) < 0) {
return nodeExist(Tree.getLeft(), value);
} else {
return nodeExist(Tree.getRight(), value);
}
}
See also
Should a function have only one return statement?
Additionally, I noticed that you used == instead of equals for object comparison (i.e. T can't be a primitive type). This is rarely correct; equals is almost always what is really intended.
See also
Difference Between Equals and ==
One more style advice, please follow naming convention for Java, where variable names start with lowercase letter, with upper case letter for internal words (so, somethingLikeThis).
Programming isn't about getting things right, it's also about getting things readable. Learn and adopt a good coding style, and follow established conventions.
In the section in which you're doing your compareTo where the th value is not set. If this conditional is met, th can never be set to true.

Categories