If statement return loop - java

Just a declaimer:i am a beginner in java.
Write a method named numUnique that takes three integers as parameters and that returns the number of unique integers among the three. For example, the call numUnique(18, 3, 4) should return 3 because the parameters have 3 different values. By contrast, the call numUnique(6, 7, 6) would return 2 because there are only 2 unique numbers among the three parameters: 6 and 7.
public int numUnique(int x,int y,int z){
    if(x==y||y==z){
}
return 1;
else if(x!=y||y!=z){
}
return 2;
    
}
I am very confused about the relationship of if and return.I always put return inside if statement.But i dont understand why does it generate me an error message.if something is fulfil,i return in the loop.Why is it wrong.But on the other hand,the println statement can be put inside for loops.
Another issue,because this question,i tried to attempt using if else too.But my first condition is if and i return it.So after that i placed else if after the first return,it gives me error again.
I will appreciate someone will explain to me and i will alter the codes on my own.Please dont give me the full codes.Thank you.
Edited*
By the way,i read through all the comments and i finally understand it.This is my codes that i work out on my own(:
public static int numUnique(int x, int y, int z) {
if(x==y && y==z){
return 1;
}else if(x==y && y!=z || y==z && z!=x || x==z && y!=z ){
return 2;
}
return 3;
}

The return statements should be placed within the curly bracets.

To give you a clear understanding of "return" statements, i will say there can be only one return statement in one block of code i.e {...}.
"return" statement is used to return to the caller, and it has to be last statement of the block.
As suggested by you i am not providing you complete code, rather making you aware of usage of "return" statement.
In your code you are writing two "return" statements in one block.

i think you need to write return statements inside if-else blocks otherwise it will always return 1

The syntax for a what you want looks like this:
public static int numUnique(int x,int y,int z){
if(x==y||y==z){
return 1;
}else if(x!=y||y!=z){
return 2;
}
return 3;
}
Maybee this code ist better understandable:
public static int numUnique(int x, int y, int z) {
if (x == y && x == z && y == z) {
return 3;
} else if (x != y && x != z && y != z) {
return 1;
}
return 2;
}
Pseudocode If
if( condition ){
// do something if condition is true
}
Pseudocode If then else
if( condition){
// do something
}else{
// do something if condition is false
}
Pseudocode elseif
if( condition ){
// do something
}else if(condition2){
// do something, only if condition2 is true, if condition 1 is true, you never will be here
}else{
// do something, your only here if the two conditions above were false
}
A return statement, immidiently brakes execution ( there are some exception, exmaple: the finally block)

First, your return are outside the if statements, they should be inside. Because if you write:
if(Something) {
}
return 1;
Then 1 will be always returned because your if is empty. If you want to return 1 only if(Something) then write it inside the if body:
if(Something) {
return 1;
}
Second, your logic is not good. You need to check:
if x == y == z then they're all equal.
if x == y and x != z then you should return 2.
if x != y != z then you should return 0.
....
You need to cover all situations.

since if is a conditional flow, i may or may not run (depending on the condition),
but if your method has return type it should return in every cases. But in the later case, (if condition is false), it wont find any return.
so if you write
public int value(boolean flag){
if(flag){
return 0; //only reachable if flag is true, else value can not return from here
}
}
it is wrong, since if flag is false method wont return anything. so you must provide a return in else or after if block ends

using the fact that Sets store values only once...
public int numUnique(int x,int y,int z){
Set<Integer> number = new HashSet<Integer>();
number.add(x);
number.add(y);
number.add(z);
return numbers.size();
}

You have to put the return statement in the block from if and else:
public int numUnique(int x,int y,int z){
if(x==y||y==z){
return 1;
}
else if(x!=y||y!=z){
return 2;
}
}
it fails because the compiler think, that you have not a return statement for the function in every path.

Your code is ill-formed:
And if-else statement is as following:
if { code }
else { code }
So, if and else blocks make a pair. But you have:
if (condition) { code }
code
else { code }
code
So, the code just above the word else breaks this pair, and else remains isolated, and thus your program is syntactically incorrect.
You "want" to do:
if (x==y || y == z) {
return 1;
}
else if (x != y || y != z) {
return 2;
}
Moreover, if a if (or else) block has only one line, you can erase the brackets:
if (x==y || y == z)
return 1;
else if (x != y || y != z)
return 2;
Even more, you algorithms isn't a solution to your problem, ¿how about 3 unique values?. You should check more situations (all diferents, all equals, or only one different).

Related

Why does my recursion fall through?

My recursive function is falling through in my program. I am making a method that constructs a relatively simple object array and populates them with certain values. i.e. object 1 has these values 3,2,5,6,7, object 2 has these values; 4,5,6,4,5. and so on
the recursion comes in when I have different parts of the method that do different things to the function. as shown below:
objectConstructor(Object foo, int switcherVar){
if(switcherVar == 1){
//terminating condition leave method
return 1;
} else {
if(switcherVar == 2){
//do something
objectConstructor(object foo, 1)
}
}
return 0;
}
When I check my return value i get a 0. The stuff that I'm actually doing in the method is unrelated to my recursive function and the function IS re cursing just at the end it falls through when its supposed to jump to the terminating condition. From my understanding the problem is the way I'm formatting my recursive function.
Below is the actual code It's an airplane seat constructor that give values to an airplanes seats, like if it is occupied and whatnot. the above is easier to read but if my syntax is off that might be the problem as well.
private int airplaneSeatConstructor(Airplane airplane, String className, int numberOfSeats){
/*Airplane Seat Creator, loops through the seats and attaches credentials to them based on the type of plane
* being formed.*/
//currently only one plane type. 777.
//777 seat number 257
//does have a first class section.
System.out.println("iteration");
if(className.equals("TERM")){
return 1;
}else {
if (className.equals("FIRST")) {
for (int x = 0; x < numberOfSeats; x++) {
airplane.getSeats()[x].setOccupied(false);
airplane.getSeats()[x].setFirstClass(true);
airplane.getSeats()[x].setBusinessClass(false);
if ((x % 4) == 0 || (x % 4) == 3) {
airplane.getSeats()[x].setWindowseat(true);
airplane.getSeats()[x].setAisleSeat(false);
} else {
airplane.getSeats()[x].setAisleSeat(true);
airplane.getSeats()[x].setWindowseat(false);
}
}
System.out.println("in first");
airplaneSeatConstructor(airplane, "BUSINESS", 40);
}
if (className.equals("BUSINESS")) {
for (int x = 0; x < numberOfSeats; x++) {
airplane.getSeats()[airplane.getNumberOfSeatsPerClass()[0] + x].setBusinessClass(true);
airplane.getSeats()[airplane.getNumberOfSeatsPerClass()[0] + x].setFirstClass(false);
airplane.getSeats()[airplane.getNumberOfSeatsPerClass()[0] + x].setOccupied(false);
}
System.out.println("in business");
airplaneSeatConstructor(airplane, "ECONOMY", 209);
}
if (className.equals("ECONOMY")) {
for (int x = 0; x < numberOfSeats; x++) {
airplane.getSeats()[airplane.getNumberOfSeatsPerClass()[0] + airplane.getNumberOfSeatsPerClass()[1] + x].setBusinessClass(false);
airplane.getSeats()[airplane.getNumberOfSeatsPerClass()[0] + airplane.getNumberOfSeatsPerClass()[1] + x].setFirstClass(false);
airplane.getSeats()[airplane.getNumberOfSeatsPerClass()[0] + airplane.getNumberOfSeatsPerClass()[1] + x].setOccupied(false);
}
System.out.println("in economy");
airplaneSeatConstructor(airplane, "SPECIAL", 26);
}
if (className.equals("SPECIAL")) {
System.out.println("in special");
airplaneSeatConstructor(airplane, "TERM", 273);
}
}
return 0;
}
my print lines all hit but I'm still getting 0 from my return value.
In your code, whatever recursion you do, in fact, whatever calculation you do is not going to count, since you're finally returning 0 for all cases but the base one (in which you return 1).
objectConstructor(Object foo, int switcherVar){
if(switcherVar == 1){
//terminating condition leave method
return 1;
} else {
if(switcherVar == 2){
//do something
objectConstructor(object foo, 1)
}
}
return 0;
}
Recursion in your program works this way: you do the first call with switcher == 2, which makes the recursive call whit switcher == 1. But then you discard that result and just return 0.
The correct or logic way of things for doing this is more similar to this:
objectConstructor(Object foo, int switcherVar){
if(switcherVar == 1){
//terminating condition leave method
return 1;
} else {
if(switcherVar == 2){
//do something
return objectConstructor(object foo, 1)
}
}
}
Hope this helps.
However, looking closely to your code, I think that you are substituting sequence by recursion. I would refactor (i.e., divide the code of) your function by classes of seats, and make the needed calls. Recursion is not needed at all in your code. See below:
private void airplaneSeatConstructorFirstClass(Airplane airplane, int numberOfSeats)
{
for (int x = 0; x < numberOfSeats; x++) {
airplane.getSeats()[x].setOccupied(false);
airplane.getSeats()[x].setFirstClass(true);
airplane.getSeats()[x].setBusinessClass(false);
if ((x % 4) == 0 || (x % 4) == 3) {
airplane.getSeats()[x].setWindowseat(true);
airplane.getSeats()[x].setAisleSeat(false);
} else {
airplane.getSeats()[x].setAisleSeat(true);
airplane.getSeats()[x].setWindowseat(false);
}
}
}
private void airplaneSeatConstructorBussinessClass(Airplane airplane, int numberOfSeats)
{
for (int x = 0; x < numberOfSeats; x++) {
airplane.getSeats()[airplane.getNumberOfSeatsPerClass()[0] + x].setBusinessClass(true);
airplane.getSeats()[airplane.getNumberOfSeatsPerClass()[0] + x].setFirstClass(false);
airplane.getSeats()[airplane.getNumberOfSeatsPerClass()[0] + x].setOccupied(false);
}
}
...and so on.
Now you just have to call:
airplaneSeatConstructorFirstClass( airplane, 80 );
airplaneSeatConstructorBussinessClass( airplane, 40 );
As you can see is far easier (unless I'm missing something big).
Let's say that this
objectConstructor(object foo, 1);
returns 1.
After that you do return 0. Of course the whole thing will return 0.
Maybe you should
return objectConstructor(object foo, 1);

Practice for breaking or returning in a loop

Background: I am making a chess game. It works almost completely, just missing the check for checkmate, but I am refining some code for readability, etc.
Right now, I am recoding a method I had to check the path from any piece, to another location on the board. It returns true if there is a piece blocking the path and false if there is not one.
Note: I do not need to check the spot of the last location because my game will check to make sure that you do not occupy the spot you are trying to move to.
Also note that I have researched this question and I have found that the consensus, mainly on here, is that breaking is the correct solution. This is preferred over having a boolean variable initialized outside the loop and set true or false and breaking the loop on that value. However, I have two conditions in my loop that may make my code return true or return false so I can't do that completely.
Current Code
public boolean isPathClear(Location l1, Location l2) {
int atx = l1.getX();
int aty = l1.getY();
int xdiff = 0, ydiff = 0;
int endx = l2.getX(), endy = l2.getY();
if(l1.getX() > l2.getX()) {
xdiff = 1;
}
if(l1.getX() < l2.getX()) {
xdiff = -1;
}
if(l1.getY() > l2.getY()) {
ydiff = 1;
}
if(l1.getY() < l2.getY()) {
ydiff = -1;
}
while(true) {
atx += xdiff;
aty += ydiff;
if(atx == endx && aty == endy) {
return true
}
if(board[atx][aty].getType() != ' ') {
return false;
}
}
Problem: Since breaking is the preferred method, that is what I planned to do. But, I came into a problem, if I use break in one of the if statements, it looks like I have to return in the other. Like:
while(true) {
atx += xdiff;
aty += ydiff;
if(atx == endx && aty == endy) {
break;
}
if(board[atx][aty].getType() != ' ') {
return false;
}
}
return true;
Question:
This seems like a sort of mix that could be confusing. So with my situation, would this still be the preferred method over this code:
boolean clear;
while(true) {
atx += xdiff;
aty += ydiff;
if(atx == endx && aty == endy) {
clear = true;
break;
}
if(board[atx][aty].getType() != ' ') {
clear = false;
break;
}
}
return clear;
Instead of while(true), you can try to handle your actual conditions inside the while loop and you don't need additional break statements:
public boolean isPathClear(Location l1, Location l2) {
int atx = l1.getX(), aty = l1.getY();
int endx = l2.getX(), enxy = l2.getY();
int xdiff = Integer.signum(endx - atx);
int ydiff = Integer.signum(endy - aty);
do{
atx += xdiff;
aty += ydiff;
} while(!(atx == endx && aty == endy) && board[atx][aty].getType() == ' ');
return atx == endx && aty == endy;
}
If you want to do it using break - it doesn't really matter - but I prefer this:
boolean notObstructed = true;
while(notObstructed) {
atx += xdiff;
aty += ydiff;
if(atx == endx && aty == endy)
break;
if(board[atx][aty].getType() != ' ')
notObstructed = false;
}
return notObstructed;
This way there's only one return statement whose value is configured based on the while loop and if statements.
Mostly I'd say it's a subjective thing.
One objective advantage to your last code sample is that it gives you a single point of exit from the method, which is frequently useful for debugging. A guy I used to work with who did military software previously said it was a requirement they had to work to: A method must only have a single exit point. His claim was that it was a robustness/reliability/maintainability thing. I just like having that easy "here's where it leaves" thing.
Use return statements. The idea is to keep it readable and maintainable. Just don't make different method calls inside those if statements and you will be fine.
Read this post from Bruce Eckel: http://onthethought.blogspot.com/2004/12/multiple-return-statements.html
Another benefit of using return statements is that another programmer is less likely to come along and modify your local variable, causing an incorrect value to be returned.
I prefer using return in these kinds of loops as i think breaks would just be a waste.
Keep a return statement at the end of your method, and use 2 regular returns in your if statements that will either return true or false.
Also last I remember coding something similar to this, since the return type of my methods were void, i could simply use:
return;
and it would exit the loop and the method.

How do I make a boolean method using a string?

This is what I have so far, I managed to reach here with several hours of work. The problem with my code is that if i give it a string "abcefg" it will verify the first two characters and returns it as true. I want the code to do it for all of my characters. I thought that putting the limit as x.length() would do the thing, but for some reason, it won't work.
public static boolean ConsecutiveCheckerAscending(String x) {
x = x.toLowerCase();
for (int i = 0; i < x.length() - 1; i++) {
if ((int)x.charAt(i) + 1 != ((int)x.charAt(i + 1)))
{
return false;
}
}
return true;
}
public static boolean ConsecutiveCheckerDescending(String x) {
x = x.toLowerCase();
for (int i = 0; i < x.length() - 1; i++) {
if((int)x.charAt(i) - 1 != ((int)x.charAt(i + 1)))
{
return false;
}
}
return true;
}
You have a variety of issues here.
Firstly, you can eventually go out of bounds with the charAt(i + 1) calls (check your loop condition).
Secondly, how can you possibly return true in the body of the for-loop? You haven't checked all of the characters yet!
I think you're making this overly complicated, though. All you need to do in order to check that two contiguous (i.e. next to each other in the string) characters are consecutive is
Math.abs(s.charAt(i) - s.charAt(i + 1)) == 1
You actually don't even need a cast. What we're doing is checking that the "distance" between the two characters is 1.
Just apply that to every contiguous pair of characters in the string, and return false if it isn't satisfied somewhere along the line. If you exit the loop without ever returning false, you can return true.
You cannot know for sure if the string is consecutive until the end of the method, so you cannot return true in the middle. At most you can return false when you find that string is not consecutive.
To give more advice, what do you mean by "consecutive"? Is adgkm consecutive? Looking at the current code it would look like it; all you check is the order of the characters. Is abcdcbcd consecutive? Usually "consecutive" means there are no gaps.
In both if and else statements you having return statement, So the method will return after first check. You have to give return only for the exit condition. don't give for both if and else
Wrote it in a rush, but it'd look something like this.-
public static boolean ConsecutiveChecker(String x) {
boolean consecutive = true;
x = x.toLowerCase();
for (int i = 0; i < x.length() - 1; i ++) {
if ((int) x.charAt(i) + 1 != ((int) x.charAt(i + 1))) {
consecutive = false;
break;
}
}
return consecutive;
}

Java boolean method needs extra return statement?

I am starting with java and while I was writing a way to identify whether a number was prime I wrote a method like this
public static boolean checkPrime(int n){
int x = 2;
while (((n % x) != 0) && (n > x)){
x = x + 1;
}
if(((n % x) == 0) && (n == x)){
return !Prime;
}
else if(((n % x) == 0) && (n > x)){
return Prime;
}
else {
return Prime;
}
}
What I couldn't figure out was the necessity of the last else statement. If I do not put it, I get an error message. However I don't think it is necessary since all possibilities are covered by the previous loops, with their respecting return statements. Or am I missing something?
You don't need the else. What you are being told by the compiler is the method must return SOMETHING. Your last else block could replaced by this:
return PrimeOrNot;
In fact, your method could look like this:
public static boolean checkPrime(int n){
int x = 2;
while (((n % x) != 0) && (n > x)){
x = x + 1;
}
if(((n % x) == 0) && (n == x)){
return !(PrimeOrNot);
}
return (PrimeOrNot);
}
In any case your very last statement block cannot be an else if.
The method has a return type of boolean.
The compiler is scared by the possibility in which none of the 'if' cases are met. In this situation, the method know what to return. This method needs to return something, so just give it a 'return true' before the method ends. It won't ever be read, but it will make the compiler happy.
The conditional expressions within the if/else-if are only evaluated at runtime. Normally, the compiler wouldn't know what the result would be, because they are not evaluated at compile-time. Only, situation when the compiler can figure what the result of the expression would be is when it's some compile-time constant (like if(true) {).
public static boolean checkPrime(int n){
boolean PrimeOrNot = false;
int x = 2;
while (((n % x) != 0) && (n > x)){
x = x + 1;
}
if(((n % x) == 0) && (n == x)){
return !(PrimeOrNot);
}
else if(((n % x) == 0) && (n > x)){
return (PrimeOrNot);
}
return PrimeOrNot;
}
A method which returns a value will be compilable if it returns a value in all its possible code paths.
Imagine for a moment that you're the compiler. You see this code:
int myMethod()
{
if (cond)
return anInt;
}
While you may know that cond is in fact always true, the compiler will not know that. It can only be sure about the result of a boolean expression if it is an expression which can be evaluated at compile time only.
Note that the vast majority of "code optimization" in Java is in fact done at run time (JIT: Just In Time).
The compiler only checks to see if there are valid return paths from your method. The compiler isn't "smart" enough to inspect the conditional statements and determine whether the conditions can be logically met -- the compiler simply checks to make sure that some value is returned to respect the contract of the method declaration.
Some would argue that the following is a cleaner structure for the method (but I think it is just a matter of taste):
public static boolean checkPrime(int n){
int x = 2;
while (((n % x) != 0) && (n > x)){
x = x + 1;
}
if(((n % x) == 0) && (n == x)){
return !(PrimeOrNot);
}
return (PrimeOrNot);
}

Some of my prime numbers are coming up as not prime [duplicate]

This question already has answers here:
.class expected error in my method and sometimes missing return statement error
(3 answers)
Closed 9 years ago.
Im not too sure whats wrong with my code, it seems like most things are coming up prime.
public static char isPrime(int x)
{
char result = 'r';
for(int y=2;y<x;y++)
{
if(x%y==0)
result = 't';
else
result = 'f';
}
return result;
}
You are always going to the end of the loop so the result will be for x-1.
You need to start with result = 't' and break out of the loop for false values.
When you just toggle like that, you throw away all previous results.
Assume it is prime until you find a composite number
public static char isPrime(int x)
{
char result = 't';
for(int y=2;y<x;y++)
{
if(x%y==0)
{
result = 'f';
break;
}
}
return result;
}
public static char isPrime(int x)
{
char result = 't';
for(int y=2;y<x;y++)
{
if(x%y==0) {
result = 'f';
break;
}
}
return result;
}
Try this:
public static boolean isPrime(int x) {
for (int y = 2; y*y <= x; y++) {
if (x % y == 0)
return false;
}
return true;
}
What was changed:
You should use boolean values to indicate that a condition is true or false, instead of the characters 't' and 'f'.
The biggest problem in your code was that, as soon as you found a divisor for your number (if (x%y==0)) you must break out of the loop, because at this point we're sure that the number is not prime, so there's no point in continuing
Only if no divisors were found, we can return true at the end, outside of the loop
You should break or return after you find out that your number is not a prime, simple as that. Additionally it seems that you return t when the number is NOT a prime.
Please use boolean and provide an Junit testcase, so we know what you exactly expect.
public static boolean isPrime(int x)
{
for(int y=2;y<x;y++)
{
if(x%y==0)
return false;
}
return true;
}
Your true and false are reversed, if its exactly divisable by something its not prime
Also, you're overwriting all your old data on each run through the loop, as soon as anything is exactly divisible then its not prime, return false at that point
Also, have you considered using the booleans true and false?
You method is not resolving prime numbers. A number is a prime if it can only be divided by one or itself.
If I input 17 into your method, for example, the result will be set to 'f' when y == 16, and that will be the returned result. However, 17 is a prime number.
You should instead try something like
for (int i = 2; i < x; i++) {
if (x % y == 0) return false;
}
return true;

Categories

Resources