My code isn't seeing the input numbers from the second class. It keeps thinking all the inputs are zero so it isn't completing the program. Where did I go wrong?
I've tried a couple different things that I could think of, but it didn't work. It keeps outputting false/unsolvable because all the numbers are zero instead of the inputs.
The second class is just the number inputs.
private static int a, b, c, d, e, f;
public static void main(String args[]) {
System.out.println("Please enter numbers for 'a, b, c, d, e, f' ");
Chapter9_2ndclass c2 = new Chapter9_2ndclass(a, b, c, d, e, f);
Exercise_09_11 Chapter9_2ndclass = new Exercise_09_11(a, b, c, d, e, f);
// Exercise_09_11 getY = new Exercise_09_11(a, b, c, d, e, f);
// //constructors
if (Chapter9_2ndclass.isSolvable()) {
Chapter9_2ndclass.getX();
Chapter9_2ndclass.getY();
} else {
System.out.println("Unsolvable");
}
}
public Exercise_09_11(int a, int b, int c, int d, int e, int f) {
this.a = a;
this.b = b;
this.c = c;
this.d = d;
this.e = e;
this.f = f;
}
public boolean isSolvable() {
double isSolvable = ((a * d) - (b * c));
System.out.println(isSolvable);
if (isSolvable != 0) {
System.out.println("True");
return true;
} else {
System.out.println("False");
System.out.println("The 'isSolvable' number is, " + isSolvable);
return false;
}
}
public int getY() {
int Y = ((a * f) - (e * c)) / ((a * d) - (b * c));
return Y;
}
public int getX() {
int X = ((e * d) - (b * f)) / ((a * d) - (b * c));
return X;
}
You are creating a new instance of Chapter9_2ndclass and Exercise_09_11, and assigning it your private static ints through their constructors.
Primitive int defaults to 0 when unassigned in this context, hence you get all 0s.
You probably want to assign them by parsing arguments of the command-line execution as int in your main method.
All variables are zero because they are not initialized and you passed the variable to the contructor of Chapter9_2ndclass and Exercise_09_11 which causes default value of int ie 0 to be passed and initializing them to 0
The problem is that you are never reading any input from the user and setting the values. Specifically, the static int declarations a, b, c, d, e, and f default to 0 and are never set.
Related
if you are replying pls show me code and tips
the code comes from bro code and im still learnin sorry
i have fixed a couple of other errors but it still doesn't work
public class main {
public static void main(String[] args) {
double x = add(1.0,2.0,3.0,4.0);
System.out.println(x);
}
static int add (int a , int b) {
System.out.println("this is a overloaded method #1");
return a + b;
}
static int add (int a , int b, int c) {
System.out.println("this is a overloaded method #2");
return a + b + c;
}
static int add (int a , int b, int c, int d) {
System.out.println("this is a overloaded method #3");
return a + b + c + d;
}
static int add (double a , double b) {
System.out.println("this is a overloaded method #4");
return a + b;
}
static int add (double a ,double b, double c){
System.out.println("this is a overloaded method #5");
return a + b + c;
}
static int add (double a , double b, int c, double d) {
System.out.println("this is a overloaded method #6");
return a + b + c + d;
}
}
enter image description here
To fix the errors, you need to do a few things:
In methods 4, 5, and 6 - update the "return type" from int to double (the one which goes after the word static)
In method 6 - update the parameter int c to double c
So your methods 4, 5, and 6 should look like this:
static double add(double a, double b) {
System.out.println("this is a overloaded method #4");
return a + b;
}
static double add(double a, double b, double c){
System.out.println("this is a overloaded method #5");
return a + b + c;
}
static double add(double a, double b, double c, double d) {
System.out.println("this is a overloaded method #6");
return a + b + c + d;
}
I'm working on this simple java recursion problem given the following directions:
Calculate the golden ratio.
Given two numbers a and b with a > b > 0, the ratio is b / a.
I have done some code but I'm stuck on getting the recursion working properly. Here's my code:
public class MyTesting {
public static void main(String[] args) {
System.out.println(ratio(8 , 4));
}
public static double ratio(int a, int b) {
int goldelRatio = 0;
if(a > b && b > 0){
return goldelRatio = a / b;
}
return goldelRatio;
}
}
How about something like this:
double goldenRatio(double a, double b, double epsilon) {
if(Math.abs((b / a) - ((a + b) / b)) < epsilon) {
return ((a + b) / b);
} else {
return goldenRatio(b, a + b, epsilon);
}
}
This way you achieve what you need in one function, with epsilon deciding how fine the resolution would be.
Also as an added bonus, and although Java doesn't have (at the time of writing this at least) tail recursion optimization, in theory this function could be optimized by tail recursion.
example with hard coded epsilon:
double goldenRatio(double a, double b) {
double epsilon = 0.00001;
if(Math.abs((b / a) - ((a + b) / b)) < epsilon) {
return ((a + b) / b);
} else {
return goldenRatio(b, a + b);
}
}
example run:
public static void main(String[] args) {
double goldenRation1 = goldenRatio(1.0, 1.0);
System.out.println(goldenRation1); // prints 1.618032786885246
System.out.println(goldenRation1 > 1.61800 && goldenRation1 < 1.61806); // prints true
double goldenRation2 = goldenRatio(100.0, 6.0);
System.out.println(goldenRation2); // prints 1.6180367504835589
System.out.println(goldenRation2 > 1.61800 && goldenRation2 < 1.61806); // prints true
}
Yours is not a recursive function, a recursive function that calculates Golden Ratio would look like the one below.
private int MAX_COUNTER = 50;
private int count = 0;
public double ratio(double a, double b) {
count++;
double goldenRatio = b / a;
if (count < MAX_COUNTER) {
return ratio(b, a + b);
}
return goldenRatio;
}
NOTE: I put the counters because given that is a recursive function trying to find a number with infinite decimals, it will cause the JVM to go on StackOverflow :) , so we got to stop it sooner or later.
Recursion mainly means methods calling themself, meaning you should try something like that:
public double recursionMethod(int a, int b){
int c = a+b;
if(Math.abs(ratio(b,a)-ratio(c,b))< (double) 1/42)
return ratio(c,b);
else
return recursionMethod(b,c);
}
1/42 is just your accuracy, you can implement any other breaking condition you like. Call this method in main with arguments (1,1).
How do I write this code in Java?
def gcd(a, b):
"""
Calculate the Greatest Common Divisor of a and b.
Unless b==0, the result will have the same sign as b (so that when
b is divided by it, the result comes out positive).
"""
while b:
a, b = b, a%b
return a
It seems I can't do while (b) { in Java because of Type mismatch error. It seems I also can't do the line a, b = b, a%b exactly in Java as well.
public static int gcd(int a, int b) {
int temp;
while(b != 0) {
temp = a;
a = b;
b = temp % b;
}
return a;
}
Java expects the condition of the while to be a boolean, not an int.
The a, b = b, a%b syntax will not work in Java. You need to do the assignments individually.
So you can set a = b, and then set b = a % b. I used a temp variable to hold the old value of a so that I can compute a % b (before I overwrote a with a = b).
Do you really need a while? It can be as simple as-
public static int gcd(int a, int b) {
if (b == 0) return a;
return gcd(b, a % b);
}
int function(int a, int b, int c){
if(a==c)
return a;
else
return b;
}
Question is to achieve a same o/p without using if, while, do, for, switch,conditional expression(?:) and other general inbuilt methods like equals
Please tell me the logic and code..
Here's one fairly straightforward option:
int function(int a, int b, int c) {
java.util.HashMap<Boolean, Integer> map = new java.util.HashMap<Boolean, Integer>();
map.put(true, a);
map.put(false, b);
return map.get(a == c);
}
Using maps to emulate switch statements in languages that don't have them is pretty common. Using them to emulate if statements is probably an abuse.
Here's an approach using operators only:
int function(int a, int b, int c) {
//If a == c: result = 0x00000000
//Else: result = 0xFFFFFFFF
int result = (a - c | c - a) >> 31;
//If a == c: result = 0x00000000 & (a ^ b) = 0
//Else: result = 0xFFFFFFFF & (a ^ b) = a ^ b
result &= a ^ b;
//If a == c: result = 0 ^ a = a
//Else: result = (a ^ b) ^ a = b
result ^= a;
return result;
}
I really wish I came up with Cairnarvon's solution. Here's what I got, but in any case you'll end up using conditional statements somewhere hidden in a function call, unless you can figure out how to do this with bitwise operators.
public static int fn(int a, int b, int c) {
Boolean equal = (a == c);
//if equal is false, compareTo will return 0.
//if equal is true, compareTo will return any positive integer, thus we take mod 2 to ensure this is 1
int ret_a = equal.compareTo(Boolean.FALSE) % 2;
//if ret_a is 0, make ret_b = 1
//if ret_a is 1, make ret_b = 0
int ret_b = (ret_a + 1) % 2;
//one of these two terms is guaranteed to be zero, therefore you will only
//return the value of a, or b.
return (ret_a * a) + (ret_b * b);
}
Here is my attempt at a solution with no comparison or bit twiddling. Sadly as #Pshemo pointed out my logic is flawed.
public static int fn(int a, int b, int c) {
//I assumed this will return 1 if not a != c
//See Pshemo's comment about why this is wrong.
int not_equal = ((a - c) * (a - c) ) % 2;
int ret_a = (not_equal + 1) % 2;
int ret_b = not_equal;
//one of these two terms is guaranteed to be zero, therefore you will only
//return the value of a, or b.
return (ret_a * a) + (ret_b * b);
}
There are a number of possible approaches, including:
Do the test in native code. That's cheating.
Find some library class that can used to do the job. There are probably lots of variations on this approach; e.g. see #Cairnarvon's answer.
Do something tricky to generate an exception (or not) depending on the inputs. My initial idea was to use division by zero, but here's another way ...
int insanelyStupidConditional (int a, int b, int c) {
int[] dummy = new int[1];
try {
int foo = dummy[a - c];
} catch (ArrayIndexOutOfBoundsException ex) {
return b;
}
return a;
}
Bit twiddling ... like #Vlad's answer
Anyway, the point of the interview question is not the answer, but whether you are able to think outside of the box to arrive at something. The most practical answer is "change the requirements ... this is insane".
Another way
Base idea return b * f(a,c) + a * (1 - f(a,c)) where
f(a,c) -> 1 for a != c
f(a,c) -> 0 for a == c
so
for a!=c we will return b*(1) + a*(0);
and for a==c we will return b*(0) + a*(1);
code
public static int test(int a, int b, int c) {
// (a - c) | (c - a) will give
// for a != b negative value
// for a == c zero
// to get sign of that value we need to get highest bit
// so >>>31 will do the trick
int signum = ((a - c) | (c - a)) >>> 31;
//for a == c -> signum = 0
//for a != c -> signum = 1 (it indicates that (a - c) | (c - a) was negative)
return b * signum + a * (1 - signum);
}
There you go, no if, while, do, for, switch, inline if (?:), or any other operator (==, !=, >, <, >=, etc.):
int function(int a, int b, int c){
int[] result = {-1, a, b};
return result[new TreeSet<Integer>(Arrays.asList(a, c)).size()];
}
Logic: Adds both a and c to a Set. If they are equal, they'll be added only once, and the set's size will be 1. If they are different, the size will be 2.
I have created a class named Times and I have to construct 4 overloaded methods. I just would like some help understanding overloaded methods and at least maybe some help with the first one. I would really appreciate it. Thanks :)
multiply 2 integers and return the (integer) product
multiply 3 integers and return the (integer) product
multiply 2 double values and return the (double) product
multiply 3 double values and return the (double) product
like this?
public class Times {
public static int multiply(int a, int b) {
return a * b;
}
public static int multiply(int a, int b, in c) {
return multiply(a, b) * c;
}
public static double multiply(double a, double b) {
return a * b;
}
public static double multiply(double a, double b) {
return multiply(a, b) * c;
}
}
"Overloaded methods" just means the methods would all have the same name (and be in the same class). The parameters need to be different either in number or type, however.
Since the all multiply stuff, "multiply" makes sense as a name.
The first one:
multiply 2 integers and return the
(integer) product
So it returns an integer (an int), is named "multiply", takes 2 ints as parameters, that gives us:
int multiply(int a, int b) {
It returns the product, so the body is:
return a * b;
And then we're done with that one:
}
That gives us:
int multiply(int a, int b) {
return a * b;
}
Use the same approach and the same name for the others.
it would look somthing like this :
public class Times {
public int mult(int a, int b) {
return a*b;
}
public int mult(int a, int b, int c) {
return a*b*c;
}
//2 more overloaded versions to come here
}
as for understanding what they mean - when your code is compiled the compiler determines which of the methods (all called the same name) to use by looking at the arguments.
so for instance for something like this
int a = 1;
int b = 1;
Times t = new Times();
t.mult(a,b);
the compiler will pick the 1st of the 2 mult methods i demonstrated, while for this:
int a = 1;
int b = 1;
int c = 2;
Times t = new Times();
t.mult(a,b,c);
it will pick the 2nd (based on the number of arguments)
You can do something like this
public class Times {
public static void main(String[] args) {
System.out.println(multiplyInt(1,2));
System.out.println(multiplyDoubles(2.0,3.0));
}
public static int multiplyInt(int... numbers){
int multiply = 1;
for(int number : numbers ){
multiply = multiply*number;
}
return multiply;
}
public static double multiplyDoubles(double... numbers){
double multiply = 1;
for(double number : numbers ){
multiply = multiply*number;
}
return multiply;
}
}