2 returns firing in the same function? - java

Well been working for hours today so i might be missing something silly, but, at this point I'm kinda blind with this and looking for an explanation for this behaviour
i made an example of the problem I'm having and the solution i found is not quite a solution.
The Problem: to the following function I pass 1 as shotCount and 9 as Countdown
the result when i debug, i see the first if run, and run the return 2, but then also the else decides to run to and finally return -1
public int getNextShot(int shotCount, int Countdown)
{
if ((shotCount == 1) && (Countdown != 10)) return 2;
else if (shotCount == 0) return 1;
else return -1;
}
BUT if i do this (same parameters) it works:
public int getNextShot(int shotCount, int Countdown)
{
int res = -2;
if ((shotCount == 1) && (Countdown != 10)) res = 2;
else if (shotCount == 0) res = 1;
else res = -1;
return res;
}
Am I missing something here?
Thanks :)

I think you are mistaken.
Sometimes the debugger in Eclipse acts like its jumping to the last line of the method call but then does return the correct value.
For example, I just copied and pasted your code and it ran fine for me. The below code prints 2.
public class AA {
public static void main(String[] args) {
System.out.println(getNextShot(1, 9));
}
public static int getNextShot(int shotCount, int Countdown)
{
if ((shotCount == 1) && (Countdown != 10)) return 2;
else if (shotCount == 0) return 1;
else return -1;
}
}

This code is OK. When I run this:
public static int getNextShot1(int shotCount, int Countdown) {
if ((shotCount == 1) && (Countdown != 10)) {
return 2;
} else if (shotCount == 0) {
return 1;
} else {
return -1;
}
}
public static int getNextShot2(int shotCount, int Countdown) {
int res = -2;
if ((shotCount == 1) && !(Countdown == 10)) {
res = 2;
} else if (shotCount == 0) {
res = 1;
} else {
res = -1;
}
return res;
}
public static void main(String[] args) throws KeyStoreException, ParseException {
System.out.println(getNextShot1(1, 9));
System.out.println(getNextShot2(1, 9));
}
I get
2
2
on console :)
Second function could look like this (final keyword):
public static int getNextShot2(int shotCount, int Countdown) {
final int res;
if ((shotCount == 1) && !(Countdown == 10)) {
res = 2;
} else if (shotCount == 0) {
res = 1;
} else {
res = -1;
}
return res;
}

Related

function to find number of ways u can split n objects using parts up to m

I'm using recursion to solve the problem. On paper my answer should work so I went wrong with the code. However, I can't figure exactly where the problem is.
public class Partition {
public static void main(String[] args) {
System.out.println(part(6,4));
}
public static int part(int n, int m) {
if (n==0) {
return 1;
}
else if(m == 0 || n<0) {
return 0;
}
else {
return part(n-m, m) + part(n, m);
}
}
}
You need to reduce m only for the problem to return 9 as you indicated.
public static int part (int n, int m) {
if (n == 0) {
return 1;
} else if (m == 0 || n < 0) {
return 0;
} else {
return part(n - m, m--) + part(n, m);
}
}
I'm not sure what you're trying to do, but if it is to compute the combination it should look like this :
public static int part(int n, int m) {
if(m>n) { //This prevent a wrong input from the user
return part(m, n);
} else if (m==0 || m==n) { //This is your base case
return 1;
} else if(m < 0 || n<0) { //this should not happened, but you never know
return 0;
} else { //this is where you're making mistake(s)
//I don't know if I'm using the formula you are looking for
//But if not, make sure yours do not use part(n, m) otherwise it will run forever
return part(n-1, m) + part(n-1, m-1);
}
}

Why does return statement is throwing error when used Math function in a method

Why does return statement is throwing error when used Math function in a method.
public class HCF_1 {
static int hcf(int a, int b)
{
int res = Math.max(a,b);
while(true)
{
if(res%a==0 && res%b==0)
return res;
else res++;
}
return res;
}
public static void main(String[] args) {
System.out.println(hcf(5,25));
}
}
This may or may not be helpful, but IMO while(true) statements are a real code smell. You can rewrite this method as:
public class HCF_1 {
static int hcf(int a, int b)
{
int res = Math.max(a,b);
while(res % a != 0 || res % b != 0)
res++;
return res;
}
public static void main(String[] args) {
System.out.println(hcf(5,25));
}
}
Now there is only a single return statement, and no shortcuts.
Note that the operations !(res % a == 0 && res % b == 0) are the same as res % a != 0 || res % b != 0, due to to the properties of Boolean Logic: ~(A AND B) == ~A OR ~B.
public class HCF_1 {
static int hcf(int a, int b)
{
int res = Math.max(a,b);
while(true)
{
if(res%a==0 && res%b==0)
return res;
else res++;
}
return res; //last line of the method hcf is unreachable
}
public static void main(String[] args) {
System.out.println(hcf(5,25));
}
}
The while loop is a never-ending loop and is escaped only under the condition mentioned inside if block which is a return statement and not a break statement. Therefore the last line of the method hcf return res; is unreachable in any condition.
the segement of your code in if-else the cause to be unreachable for the last line of your return res, you so have to do 2 things:
remove the return inside if and add break instead.
return the last line of method which is return res;
public class HCF_1 {
static int hcf(int a, int b) {
int res = Math.max(a, b);
while (true) {
if (res % a == 0 && res % b == 0)
break;
else
res++;
}
return res;
}
public static void main(String[] args) {
System.out.println(hcf(5, 25));
}
}

Recursion java modified Fibonacci

public class ModFib
{
public static int modFibonacci(int term)
{
if(term == 1)
{
return 3;
}
else if(term == 2)
{
return 5;
}
else
{
return modFibonacci(term - 1) + modFibonacci(term - 2) + modFibonacci(term - 3);
}
}
}
it works fine at only term - 3 but this gives a stack overflow error.
need to add condition like
if(term == 0)
{
return 0;
}

Making method to give value of m or M based on position

So i have to make a method that will return a value based on m or M in a string. so far i have this
public static int mIndex(String x) {
if (x.indexOf('M') >= 0) {
return x.indexOf('M');
}
if (x.indexOf('m') >= 0) {
return x.indexOf('m');
} else {
return -1;
}
}
The problem is that it only returns M if it is first in the String. Is there anyway for it to detect m or M, and then give a value based on that?
For something like that, a regular expression is your friend:
public static int mIndex(String x) {
Matcher m = Pattern.compile("[mM]").matcher(x);
if (m.find())
return m.start();
return -1;
}
Test
System.out.println(mIndex("kamdkMMM"));
System.out.println(mIndex("KAMDKmmm"));
System.out.println(mIndex("Hello World"));
Output
2
2
-1
Try this:
String s = "MarshmallowmmMaM";
System.out.println("Index of 'M':");
int index = s.indexOf("M");
while (index >= 0) {
System.out.println(index);
index = s.indexOf("M", index + 1);
}
System.out.println("Index of 'm':");
index = s.indexOf("m");
while (index >= 0) {
System.out.println(index);
index = s.indexOf("m", index + 1);
}
Output:
Index of 'M':
0
13
15
Index of 'm':
5
11
12
If you want to detect the first position of each case for letter M. "upper&lower".
public class Main {
public static int M_POSITION = -1;
public static int m_POSITION = -1;
public static void mIndex(String x) {
int i = 0;
while (i < x.length()) {
if (x.charAt(i) == 'M') {
if (M_POSITION == -1)
M_POSITION = i;
} else if (x.charAt(i) == 'm') {
if (m_POSITION == -1)
m_POSITION = i;
}
++i;
}
}
public static void main(String[] args) {
mIndex("adsm");
System.out.println(m_POSITION);
System.out.println(M_POSITION);
}
}

Recursive method checking whether a row of integers is descending: return true/false

I have to write a recursive method in Java that returns true if a row is descending and false it does not.
This is what I tried, but it doesn't work properly:
ArrayList<Integer> getallen = new ArrayList();
getallen.add(500);
getallen.add(400);
getallen.add(300);
getallen.add(200);
getallen.add(100);
getallen.add(0);
System.out.println(isDescending(getallen));
}
public static boolean isDescending(ArrayList<Integer> getallen) {
if (getallen.size() >= 2) {
if (getallen.get(0) < getallen.get(1)) {
return false;
} else if (getallen.size() > 0) {
getallen.remove(0);
return isDescending(getallen);
} else {
return true;
}
} else {
return false;
}
}
I think you have unnecessary cases if the size is less than 2 you can only assume true.
Try:
public static boolean isDescending(ArrayList<Integer> getallen) {
if (getallen.size() >= 2) {
if (getallen.get(0) < getallen.get(1)) {
return false;
} else {
getallen.remove(0);
return isDescending(getallen);
}
} else {
return true;
}
}
If I had to grade this, it would get a big fat X for
Having been fraudulently asked on stackoverflow
Being quite inefficient (try running this test on a list of a million elements, then realise that removing element 0 in an ArrayList causes all elements to shift down)
Instead consider:
public static boolean isDescending(List<Integer> getallen) {
return isDescending(getallen, 0);
}
public static boolean isDescending(List<Integer> getallen, int from) {
return from >= getallen.size() - 1
|| getallen.get(from) < getallen.get(from + 1)
&& isDescending(getallen, from + 1);
}
How about little bit more efficient approach with logarithmic recursion depth? Just as an exercise.
public static void main(String[] args) {
List<Integer> getallen = new ArrayList<Integer>();
getallen.add(500);
getallen.add(400);
getallen.add(300);
getallen.add(200);
getallen.add(100);
getallen.add(0);
System.out.println(isDescending(getallen));
}
public static boolean isDescending(List<Integer> getallen) {
return isDescending(getallen, 0, getallen.size());
}
private static boolean isDescending(List<Integer> getallen,
int start, int end) {
if (end - start <= 1)
return true;
if (end - start == 2) {
return getallen.get(start) > getallen.get(start + 1);
}
int middle = (start + end - 1) / 2 + 1;
return (getallen.get(middle - 1) > getallen.get(middle)) &&
isDescending(getallen, start, middle) &&
isDescending(getallen, middle, end);
}

Categories

Resources