return statements are not coming out right - java

I need to code a method that checks if:
A = all numbers are equal.
B = no numbers are equal.
C = at least two numbers are equal.
Im just beginning to learn all this in uni but I cant seem to figure out what i am doing wrong in this method which needs to return the given conditions e.g("A", "B", "C").
public static int checkNumbers(int x, int y, int z)
{
int A,B,C;
A = 'A';
B = 'B';
C = 'C';
if((x == y) && (y == z))
{
return A;
}
else if ((x == y) || (x == z) || (y == z))
{
return C;
}
else
{
return B;
}
}

You have declared A, B and C as integers and then assigned to them a 'Char'.
Maybe try
public static char checkNumbers(int x, int y, int z)
{
char A,B,C;
A = 'A';
B = 'B';
C = 'C';
if((x == y) && (y == z))
{
return A;
}
else if ((x == y) || (x == z) || (y == z))
{
return C;
}
else
{
return B;
}
}
Alternatively, use a String
public static String checkNumbers(int x, int y, int z)
{
String A,B,C;
A = "A";
B = "B";
C = "C";
if((x == y) && (y == z))
{
return A;
}
else if ((x == y) || (x == z) || (y == z))
{
return C;
}
else
{
return B;
}
}

return the given conditions e.g("A", "B", "C")
Then you should return a String (or char), not int.
public static String checkNumbers(int x, int y, int z) {
if (x == y && y == z) {
return "A";
} else if (x == y || x == z || y == z) {
return "C";
} else {
return "B";
}
}
public static void main(String[] args) {
System.out.println(checkNumbers(0, 0, 0)); // A
System.out.println(checkNumbers(0, 0, 1)); // C
System.out.println(checkNumbers(0, 1, 2)); // B
}
Otherwise, you need to print (char) checkNumbers(...) to cast the int return value into a printable character

Related

Recursive Longest Common Substring (LCS) problem optmization

I have the following code in Java:
public static int Secret(String a, String b, int x, int y){
if ((x == -1) || (y == -1)) {
return 0;
}
if (a.charAt(x) == b.charAt(y)) {
return Secret(a, b, x-1, y-1) + 1;
} else {
int left = Secret(a, b, x, y-1);
int up = Secret(a, b, x-1, y);
if (left > up) {
return left ;
} else {
return up;
}
}
return -1;
}
This code looks like the Longest Common Substring Problem but with a garbage complexity. I am supposed to opmitize it to O(mn) (space and time).
I tried following the algorithm on the wikipedia (https://en.wikipedia.org/wiki/Longest_common_substring_problem), that is O(mn) (space and time).
public static int iterativeLCS(String a, String b, int x, int y) {
int[][] L = new int[x+1][y+1];
int z = 0;
for (int i = 0; i <= x; i++) {
for (int j = 0; j <= y; j++) {
if (a.charAt(i) == b.charAt(j)) {
if ((i == 0) || (j == 0)) {
L[i][j] = 1;
} else {
L[i][j] = L[i-1][j-1] + 1;
}
if (L[i][j] > z) {
z = L[i][j];
}
} else {
L[i][j] = 0;
}
}
}
}
But the results don't match for some inputs. For example:
xalmandriatico
talcolaritriom
13
13
Expected output (using the recursive alg): 8
Actual output (using the iterative alg from wikipedia): 2
Any idea on what I have to do?

Boolean method to determine consecutive numbers

Write a method named consecutive that accepts three integers as parameters and returns true if they are three consecutive numbers; that is, if the numbers can be arranged into an order such that there is some integer k such that the parameters' values are k, k+1, and k+2. Your method should return false if the integers are not consecutive. Note that order is not significant; your method should return the same result for the same three integers passed in any order.
For example, the calls consecutive(1, 2, 3), consecutive(3, 2, 4), and consecutive(-10, -8, -9) would return true. The calls consecutive(3, 5, 7), consecutive(1, 2, 2), and consecutive(7, 7, 9) would return false.
This is what I have so far and keep getting infinite loop error and skipped tests
public boolean consecutive(int x, int y, int z) {
Scanner kb = new Scanner(System.in);
x = kb.nextInt();
y = kb.nextInt();
z = kb.nextInt();
if (((x < y && x < z) && (y < z && ((y - x) == 1) && ((z - x) == 2))) 
||((z < y && ((z - x) == 1) && ((y - x) == 2)))) 
{
return true;
} else if (((y < x && y < z)&& (x < z && ((x - y) == 1) && ((z - y) == 2))) 
|| ((z < x && ((z - y) == 1) && ((x - y) == 2))))
{
return true;
} else if (((z < x && z < y)&& (y < x && ((y - z) == 1) && ((x - z) == 2))) 
||((x < y && ((x - z) == 1) && ((y - z) == 2))))
{
return true;
} else {
return false;
}
What you have there is serious overkill and pretty much unreadable to anyone who hasn't spent a large proportion of their career in C :-)
You should always strive for readability (and hence maintainability) first, reverting to less readable code only when absolutely necessary. Even if you do revert, you should then document why and what you've done so the next poor soul that has to maintain your code won't be cursing your name.
For this specific case, what you are attempting can be achieved in much simpler code such as the following (pseudo-code):
def areConsecutive(a, b, c):
if a > b: swap a, b
if b > c: swap b, c
if a > b: swap a, b
return (b - a == 1) and (c - b == 1)
The three if statements are simply an unrolled bubble sort to ensure a, b and c are in ascending order, then you simply check to ensure the difference between them is one in both cases.
There's no need to put them into a list or array to sort them since sorting three items is relatively easy (the swap can be done with int t = a; a = b; b = t;).
In terms of Java code (once you've moved the input to outside the function where it belongs), you'd end up with something like:
bool areConsecutive(int a, int b, int c) {
int t;
if (a > b) { t = a; a = b; b = t; }
if (b > c) { t = b; b = c; c = t; }
if (a > b) { t = a; a = b; b = t; }
return (b - a = 1) && (c - b == 1);
}
When you are passing value why using scanner?
Remove those lines and its working. You can use another logic to determine consecutive numbers.
public boolean consecutive(int x, int y, int z) {
if (((x < y && x < z) && (y < z && ((y - x) == 1) && ((z - x) == 2))) ||((z < y && ((z - x) == 1) && ((y - x) == 2)))) {
return true;
} else if (((y < x && y < z)&& (x < z && ((x - y) == 1) && ((z - y) == 2))) ||
((z < x && ((z - y) == 1) && ((x - y) == 2)))){
return true;
} else if (((z < x && z < y)&& (y < x && ((y - z) == 1) && ((x - z) == 2))) ||((x < y && ((x - z) == 1) && ((y - z) == 2)))){
return true;
} else
return false;
}
Just Remove these code:
Scanner kb = new Scanner(System.in);
x = kb.nextInt();
y = kb.nextInt();
z = kb.nextInt();
Or use Like this:
public class test{
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
x = kb.nextInt();
y = kb.nextInt();
z = kb.nextInt();
System.out.println("Result:" + consecutive(x, y, z));
}
public static boolean consecutive(int x, int y, int z) {
if (((x < y && x < z) && (y < z && ((y - x) == 1) && ((z - x) == 2))) || ((z < y && ((z - x) == 1) && ((y - x) == 2)))) {
return true;
} else if (((y < x && y < z) && (x < z && ((x - y) == 1) && ((z - y) == 2)))
|| ((z < x && ((z - y) == 1) && ((x - y) == 2)))) {
return true;
} else if (((z < x && z < y) && (y < x && ((y - z) == 1) && ((x - z) == 2))) || ((x < y && ((x - z) == 1) && ((y - z) == 2)))) {
return true;
} else {
return false;
}
}
}
Create a list with the numbers, sort it and do de diference between the elements:
public static boolean myConsecutive(int x, int y, int z) {
final List<Integer> list = new ArrayList<>();
list.add(x);
list.add(y);
list.add(z);
Collections.sort(list);
return (list.get(2) - list.get(1) == 1 && list.get(1) - list.get(0) == 1);
}
The consecutive method is passed with three values , then why you are reading from the console.
create an array with the size of 3 elements.
Sort the arrays using Arrays.Sort method
Check the difference between the second and the first number is 1 and difference between Third and the second number is 1.
Code :
public boolean consecutive(int x, int y, int z) {
int [] numbers = new int [3];
numbers[0] = x;
numbers[1] = y;
numbers[2] = z;
Arrays.sort(numbers);
boolean isConsecutive = (numbers[1]==numbers[0]+1)&&(numbers[2]==numbers[1]+1);
return isConsecutive;
}

Java, covert recusrion into one loop

I want to convert this method into one loop, any kind of loop is fine i find it hard to convert from recursion.
public class Problem5
{
public double getRoot(double a, double b)
{
double x = (a + b)/2;
if (b - a <= 0.00)
return x;
double y = getValue(x);
if(y < 0)
return getRoot(x, b);
else
return getRoot(a, x);
}
public double getRoot(double a, double b) {
while (true) {
double x = (a + b)/2;
if (b - a <= 0.00)
return x;
double y = getValue(x);
if(y < 0)
a = x;
else
b = x;
}
throw new AssertionError("should not happen");
}

The values in the if statement is not returning, only returning the else statement (can't run it in the main class)

This subclass won't go through the if statements but only return the else statement so it only returns 0. Also, the main class and subclass are separate java classes.
public class LargestEven {
int largestEven(int x, int y, int z) {
if(x % 2 == 0 && x >= y && x >= z) {
return x; // this part won't return
}
if(y % 2 == 0 && y >= x && y >= z) {
return y; //this part also won't return
}
if(z % 2 ==0 && z >= x && z >= y) {
return z; //this too won't return
}
else {
return 0;
}
}
}
Your code requires that a number is both the largest and even. In your example with values (2, 4, 9), you will not get back 4, because 4 is the largest even between these numbers, but not the largest, i.e. this is not true: y>=z.
You would need to change your checks, so that you only check the valid cases:
public class LargestEven {
int largestEven(int x, int y, int z) {
boolean xIsEven = x%2 == 0;
boolean yIsEven = y%2 == 0;
boolean zIsEven = z%2 == 0;
//checks that x is even and greater from y and z if y and z are
//even respectively
if (xIsEven && (!yIsEven || x>=y) && (!zIsEven || x >= z)) {
return x; // this part won't return
}
//we know for sure that x is not the largest even
//so we skip checking it
if (yIsEven && (!zIsEven || y>=z)) {
return y;
}
//we know that neither x or y are the largest evens
//so return either z if z is even, or 0
return zIsEven ? z : 0;
}
}
It does not appear to be an issue with your function logic... see below, the same function in JS.
function largestEven(x, y, z) {
if (x % 2 == 0 && x >= y && x >= z) {
return x; // this part won't return
}
if (y % 2 == 0 && y >= x && y >= z) {
return y;
}
if (z % 2 == 0 && z >= x && z >= y) {
return z;
} else {
return 0;
}
}
var ele = document.getElementById("result");
ele.innerHTML += "<p>Sending 2, 3, 4 (position z): " + largestEven(2,3,4)+"</p>";
ele.innerHTML += "<p>Sending 3, 4, 2 (position y): " + largestEven(3,4,2)+"</p>";
ele.innerHTML += "<p>Sending 4, 3, 2 (position x): " + largestEven(4,3,2)+"</p>";
ele.innerHTML += "<p>Sending 2, 2, 2 (position x): " + largestEven(2,2,2)+"</p>";
ele.innerHTML += "<p>Sending 3, 3, 3 (no largest): " + largestEven(3,3,3)+"</p>";
<div id="result"></div>

Multiply without multiplication, division and bitwise operators, and no loops. Recursion

public class MultiplyViaRecursion{
public static void main(String[] args){
System.out.println("8 * 9 == " + multiply(8, 9));
System.out.println("6 * 0 == " + multiply(6, 0));
System.out.println("0 * 6 == " + multiply(0, 6));
System.out.println("7 * -6 == " + multiply(7, -6));
}
public static int multiply(int x, int y){
int result = 0;
if(y > 0)
return result = (x + multiply(x, (y-1)));
if(y == 0)
return result;
if(y < 0)
return result = -multiply(x, -y);
return result;
}
}
My question is very simple and basic, why after each "if" the "return" still cannot pass the compilation, error shows missing return.
To put it simply: the Java compiler isn't that smart. It can't deduce that one of your three if statements must evaluate to true. And since the compiler believes there is a chance all the if conditions can fail, it thinks it's possible to go beyond the if blocks, at which point there is no return statement.
Instead, try using an if else block, like so.
public static int multiply(int x, int y) {
int result = 0;
if (y > 0)
return result = (x + multiply(x, (y - 1)));
else if (y == 0)
return result;
else
return result = -multiply(x, -y);
}
Because the compiler cannot guess that your three IFs cover all the cases.
If you want to simplify the code, you can remove the last IF that is unnecessary :
public static int multiply(int x, int y){
int result = 0;
if(y > 0)
return result = (x + multiply(x, (y-1)));
if(y == 0)
return result;
return result = -multiply(x, -y);
}
By the way, you can also remove the result variable :
public static int multiply(int x, int y){
if(y > 0)
return (x + multiply(x, (y-1)));
if(y == 0)
return 0;
return -multiply(x, -y);
}

Categories