This is the question in Coding bat(the Java version)::
Given an array of ints, return true if the array contains a 2 next to a 2 somewhere.
has22({1, 2, 2}) → true
has22({1, 2, 1, 2}) → false
has22({2, 1, 2}) → false
This was my solution:
public boolean has22(int[] nums) {
for (int i=0; i<nums.length-1;i++) {
if (nums[i]==2 && nums[i+1]==2) {
return true;
}
else {
return false;
}
}
}
Doesn't compile while this does..
public boolean has22(int[] nums) {
for (int i=0; i<nums.length-1;i++) {
if (nums[i]==2 && nums[i+1]==2) {
return true;
}
else {
}
}
return false;
}
Sorry if this is a stupid question but I'm confused about the brackets at the end.
Imagine a case when your argument is empty or null. Your first method doesn't compile, because it doesn't return a boolean value for all cases.
Your second method compiles, because it will return a boolean value in any case, after the iteration is complete.
public boolean has22(int[] nums)
{
for (int i=0; i<nums.length-1;i++)
if (nums[i]==2 && nums[i+1]==2)
return true;
return false;
}
You can write your program like above no need of braces.
for each conditional statement one statement is always there if we want to associate more than one statement with any conditional statement then we provide {} braces for example
if(some condition)
stmt1;
no need of braces but if more than one statement then
if(some condition)
{
stmt1;
stmt2;
}
so always remember more than one statement braces compulsory and to avoid problem when ever open a bracket just close at the same time and write inside that one it will let you some relax.
Thanks
asif aftab
Related
I wrote a piece of code which should be executed until the condition is satisfied. I have 2 classes using the same structure. In one of them while (true) loop executes as expected; in the other class the program exits the loop after the first recursion.
protected static boolean flag = true;
private static int value=0;
private static int limit=10;
.
.
.
public static int method(){
if (limit-value <=0)
{
...
}
else {
while(flag) {
if (limit-value > 0 ) {
*the action I want to perform until the condition is satisfied*
value++;
}
else if (limit==value)
{
flag = false;
}
return int_Value;
}
}
}
return int_Value;
}
I expect the while(true) loop to be executed until the condition is satisfied (which is more than once).
With some cleaned up indentation it becomes clear that the while loop contains an unconditional return.
if you look at your code the while loop goes like this
while(flag) {
if (limit-value > 0 ) {
*the action I want to perform until the condition is satisfied*
value++;
}
else if (limit==value)
{
flag = false;
}
return int_Value;
}
after executing either if or if else statement there is a return int_value statement which is causing the problem
Although I did debugging I couldn't see it in the first place. I performed another debug session after #user3437460 's suggestion, so I was able to find out:
It seems like an additional return statement was used!(return int_Value;),
the one after else if block. So, the program returns a value and never goes back into the loop.
After deleting the first return statement, program runs just fine.
So I'm trying to find whether array a is a subset of array b, and my code is as follows :`
public class subset {
public static boolean subset(int[]a, int[] b) {
for(int i=0;i<a.length;i++){
for(int j=0;i<a.length;j++){
if(a[i]==b[j]){
return true;
break;
}else{
return false;
}
}
}
}
public static void main(String[]args){
int[] a = {1,2,6};
int[] b = {1,2,4,3,7,4,8,5};
if (subset(a,b))
System.out.println("Array 1 is contained in Array 2");
else
System.out.println("Array 1 is not contained in Array 2");
}
}
And I am getting the following errors: unreachable statement and missing return statement.
What I want to do is that when the if condition is true it stops the inner for loop and carries on with the outer for loop.
Thanks in advance
2 things need to be fixed. You need to remove break, and add a return false at the end.
public static boolean subset(int[]a, int[] b) {
for(int i=0;i<a.length;i++){
for(int j=0;i<a.length;j++){
if(a[i]==b[j]){
return true;
//break; remove this
}else{
return false;
}
}
}
return false; //add this
}
Also, you could simplify it a bit, by doing this, instead of the if..else
return a[i]==b[j];
First problem is this:
return true;
break;}
the second line will never be executed because the first one terminates the method execution. Decide which line you want here: return a value or jump out of the inner loop (neither I presume, this branch should be empty, see below).
The second problem is that when you pass in an empty array the loops are not executed and the method does not have a value to return. Here simply add a "return true" (or false, quite arbitrary here) at the end of the method.
You probably can simplify the loop body in this way:
if(a[i]!=b[j]){
return false;
}
This is my method to find if a particular node is there in a binary tree.Here's my method and it works fine.
public boolean find(BinaryNode p,int x){
if(p==null){
return false ;
}
else{
if(x==p.element){
return true;
}
else if(x<p.element){
return find(p.left,x);
}
else {
return find(p.right,x);
}
}
}
My question is if I don't insert return keyword inside else if(x<p.element){ and else { I get an error as missing return statement.
Say I have a binary tree consisting of elements 5,4,6,60,25,10 .
So if i am searching for 10 there's a time that
if(x==p.element){
return true;
is satisfied because of recursive calls.Then there's a return statement to be found.
If i am searching for an element that's not in tree eventually I would reach the statement
if(p==null){
return false ;
},there we find a return statement.
Therefore even I don't have the return in else if and else clauses somehow there's a way that I finally reach a return statement right?So what's wrong with not having return keyword in else if and else clauses.
Why do I have to have it there?
Why can't I do it as
`public boolean find(BinaryNode p,int x){
if(p==null){
return false ;
}
else{
if(x==p.element){
return true;
}
else if(x<p.element){
find(p.left,x);
}
else {
find(p.right,x);
}
}
}`
The closest to the way you want your if-else if-else clause to behave is using the ? conditional expression:
public boolean find(BinaryNode p,int x)
{
if(p==null) {
return false ;
}
else {
return (x==p.element)?true:(x<p.element?find(p.left,x):find(p.right,x));
}
}
Other option is to store the value to be returned in a local variable and only return it at the end of your method:
public boolean find(BinaryNode p,int x)
{
boolean returnValue = false;
if(p!=null)
{
if(x==p.element){
returnValue = true;
}
else if(x<p.element){
returnValue = find(p.left,x);
}
else {
returnValue = find(p.right,x);
}
}
return returnValue;
}
And my favorite way, using short-circuit evaluation of logical expressions:
public boolean find(BinaryNode p,int x)
{
if(p==null) return false;
return x==p.element || (x<p.element && find(p.left,x)) || find(p.right,x);
}
Since Java's || and && operators won't evaluate their right part expression when the left part already determines their result. If x==p.element is true, then true will be returned without evaluation the rest of the line. If not, then (x<p.element && find(p.left,x)) will be evaluated following the same rule.
Note how find(p.left,x) won't be evaluated when x<p.element is false.
You need return statement because the find-function in the else if - else statement will return to the caller after its done, but the first-call function still have to return a value to the caller
Therefore even I don't have the return in else if and else clauses somehow there's a way that I finally reach a return statement right?
No compiler doesn't know about it. Compiler doesn't know what will be value of x and p at run-time.
Compiler simply checks for all the possibilities of the return statement and there must be exit point of the method.
You need to provide the logic to move either in right direction or left direction of the binary tree.
The last two else-if are not responsible to actually return the result of the find method its used just to move in the right direction of the tree. Ultimately final result of the the find method will come out by first two if-else clause.
I'm trying to make a boolean method, but it's not recognizing I have a return statement. What should I do?
public boolean isThreeKind( int rankHist[]) {
for (int i=0;i<=13;i++){
if (rankHist[i]>=3){
return true;
}else{
return false;
}
}
}
Your code does not make sense. There is no point in having a loop if you're always going to run the code inside the loop exactly once. I think you must have misunderstood. What are you trying to do?
Assuming the method only has to return true or false if it is greater than equal to 3,
would recommend to keep it simple.
Also, Please Note:
Loop through the i=0 to i< rankHist.length incase the array contains less than 13 elements you will encounter an ArrayOutOfBoundException.
If it contains more than 13 elements, the output might be incorrect.
.
public boolean isThreeKind( int rankHist[]) {
for (int i=0;i<rankHist.length;i++){
if (rankHist[i]>=3){
return true;
}
}
return false;
}
I think what he wants is if every element in the 13 are >=3, he should return a true, else ways he should return a false.
public boolean isThreeKind( int rankHist[])
{
for (int i=0;i<=13;i++)
{
if (rankHist[i]<3)
{
return false; // Will return false if either of the element have value <3
}
}
return true; // Will return true only if all the 13 elements have value >=3
}
This is literally what your code is doing right now:
public boolean isThreeKind( int rankHist[]) {
return rankHist[0] >= 3;
}
That is it, and I am assuming this is not what you are attempting to do. So if you tell us what you are actually trying to accomplish we can help you more.
In java, You always gotta keep track of returning something EVERYWHERE the method can exit. If it can exit without hitting a return statement, you'll see that error.
So, for your code, to modify it and make it see it, you would need to have it say:
public boolean isThreeKind( int rankHist[]) {
for (int i=0;i<=13;i++){
if (rankHist[i]>=3){
return true;
}else{
return false;
}
}
return false;
}
Or true, if you would rather that.
You should avoid multiple return statement.
You can use a flag. Declare the flag outside the for loop, then assign the value accordingly, and do not miss the break statement.
Do it like that:
public boolean isThreeKind( int rankHist[]) {
boolean value = false;
for (int i=0;i<=13;i++){
if (rankHist[i]>=3){
value = true;
break;
}
}
return value;
}
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.