How do I simplify this code with a conditional operator in Java?
This is from dr. Liang's Introduction to Java.
public class Test {
public static void main(String[] args) {
int i = 3;
int j = 4;
int k = max(i, j);
System.out.println("The max int is " + k);
}
public static int max(int num1, int num2) {
int result;
if (num1 > num2) {
result = num1;
}
else {
result = num2;
}
return result;
}
}
You can turn things into a one-liner using the conditinal ternary operator:
return (num1 > num2) ? num1 : num2;
But just for the record: it would be better to keep that max method around; simply for the sake of readability. It helps to have that functionality in its own method.
But of course: you want to read about java.lang.Math.max() which already provides exactly that functionality (not only for int, but all the other numerical primitive types as well)!
So, the real answer is: yes, use a method for that check; but don't create your own version; use the one that is already coming with Java by default. In other words: do not re-invent the wheel. Even when it is just a small wheel like this one.
While you could use the conditional operator ? : to implement this
public static int max(int num1, int num2) {
return num1 > num2 ? num1 : num2;
}
But, I would prefer Math.max(int, int) like
public static int max(int num1, int num2) {
return Math.max(num1, num2);
}
You might also choose to use varargs and support an arbitrary number of int(s). Using an IntStream you could do
public static int max(int... nums) {
return IntStream.of(nums).max().getAsInt();
}
You can use a conditional ternary operator.
int k = (i > j) ? i : j;
This expression evaluates to:
If i is greather than j, assign i to k. If not, assign j to k.
This would be one way to modify your example to use the ternary operator.
You should generally keep the values in the operator short otherwise they get hard to read.
public class Test {
public static void main(String[] args) {
int i = 3;
int j = 4;
int k = max(i, j);
System.out.println("The max int is " + k);
}
public static int max(int num1, int num2) {
int result;
result = (num1 > num2) ? num1 : num2;
return result;
}
}
Related
This question already has answers here:
Is floating point math broken?
(31 answers)
Closed 1 year ago.
My task is to compare two numbers and return true if they are equal by three decimal places. When I print out the value of diff it is 0.0001, but it still doesn't enter the if(diff <= 0.0001) block.
public class DecimalComparator {
public static boolean areEqualByThreeDecimalPlaces(double num1, double num2) {
double diff = Math.abs(num1 - num2);
System.out.printf("%f", diff);
if(diff <= 0.0001) {
return true;
} else {
return false;
}
}
public static void main(String[] args) {
boolean test = areEqualByThreeDecimalPlaces(3.1756, 3.1755);
System.out.println(test);
test = areEqualByThreeDecimalPlaces(3.176, 3.175);
System.out.println(test);
}
}
When you need arbitrary precision use BigDecimal. Also, your magic number should be 0.001 for three decimal places. Like,
public static boolean areEqualByThreeDecimalPlaces(double num1, double num2) {
return new BigDecimal(num1).subtract(new BigDecimal(num2)).abs()
.compareTo(new BigDecimal(0.001)) <= 0;
}
public static void main(String[] args) {
System.out.println(areEqualByThreeDecimalPlaces(3.1756, 3.1755));
System.out.println(areEqualByThreeDecimalPlaces(3.176, 3.175));
}
Outputs
true
false
While I believe #Elliot Frisch has the best Java approach, it is always difficult to know if one should introduce concepts beyond the standard primitives for what appears to be homework.
In the alternative, knowing that the desired value is 3 decimal places, the problem may be re-conceptualized by multiplying by 1000 and using an int.
Example:
public static boolean areEqualByThreeDecimalPlaces(double num1, double num2) {
final int mult = 1000;
int i1 = (int)(num1 * mult);
int i2 = (int)(num2 * mult);
return (Math.abs(i1 - i2)) == 0;
}
The output shows the expected true and false for the test cases.
Just an alternative approach to consider if one cannot switch to using other Java classes.
How do I obtain the max value of both the given int and double values?
package _pasted_code_;
import java.util.Scanner;
public class extra {
public static void main(String[] args) {
double x = 2.0;
double y = 3.0;
double z = 5.67;
int a = 3;
int b = 9;
double answer = max(x, y);
System.out.println("The largest number is: " + answer);
double answer = max(x, y, z);
int max = max(a, b);
}
public static double max(double num1, double num2) {
if (num1 > num2)
return num1;
else
return num2;
}
public static int max (int x, int y) {
if (x > y)
return x;
else
return y;
}
public static double max(double num1, double num2, double num3) {
if ((num1 > num2) && (num1 > num3))
return num1;
else
return num2;
else
return num3;
}
}
You can use Math.max(double a, double b)
and Math.max(int a, int b)
Example:
public static int max(int x, int y) {
return Math.max(x, y);
}
public static double max(double num1, double num2) {
return Math.max(num1, num2);
}
public static double max(double num1, double num2, double num3) {
return Math.max(Math.max(num1, num2), num3);
}
Java will convert an int to a double when needed. Also, just use Java's Math.max().
Like previously stated, you could use the Math.max method inside your code to receive the max number. same with the Math.min(x,y). They both work the same way.
therefore lets put it in simple terms.
public static double max(double num1, double num2)
{
return Math.Max(num1, num2);
}
also
public static int max (int x, int y)
{
return Math.max(x,y);
}
It's quite simple. I believe someone might've answered it already, but it's the same concept.
The best practice here is to use method overloading (Assuming that you do not want to use Java's own max/min method). Any method has its own signature and they are uniquely identified with the signatures. So, what I would recommend is defining method as follows:
public static int max(int x, int y) {
// your implementation
}
public static double max(double x, double y) {
// your implementation
}
But remember, it is always better to use Java's min, max methods.
First off, if you just use parameters of type double, Java will automatically perform a primitive conversion from int to double.
Second, you can indeed use Math.max of compare the two, returning the highest value.
However, if you have many doubles to compare, it will become cumbersome to write Math.max for each comparison. In that case, I suggest using a stream:
double[] numbers = ...;
double max = Arrays.stream(numbers)
.max()
.get();
Note: this will throw an Exception if the array is empty.
I am trying to write a function in java that finds the result of an operand raised to the power of another.
I can't use the pow function or any form of loop. What are any possible solutions? I tried "^" and that didn't work.
public static String raiseP(int op1, int op2){
int result = op1 ^ op2; //Doesn't Work
return result;
}
Would there be a way to do this using basic math?
I have written:
public static int pow(int x, int y, int n, int z){
if (y == n){
System.out.println(z);
return z;
}
else{
z = z*x;
n += 1;
pow(x,y,n,z);
return 0;
}
}
ex: pow(5,9,0,1) == 5^9
but am not allowed to use recursion.
Without being able to call Math.pow or using loops, the only other possibility is using recursion:
public int powerFunction(int base, int exponent) {
if(exponent < 0){ throw new IllegalArgumentException("unsupported negative pow"); }
if(exponent == 0){ return 1; }
else{
return base * powerFunction(base, exponent - 1);
}
}
Calling powerFunction(2, 3) will give you: 1 * 2 * 2 * 2 = 8
You could simply use that
pow(x,y) = exp(y*log(x))
which is also part of the implementation of the power function in the math library.
The recursion could help you:
public static int myPowerRec(int op1, int op2, int res) {
if (op2 == 0) {
return res;
}
else {
return (myPowerRec(op1, op2 - 1, op1 * res));
}
}
You will need to initialize res to 1 (myPowerRec(23, 2, 1) will give you 1 * 23 * 23).
This recursion is called tail recursion and will allow you to use this function without stack problem.
Be careful, you must check op2 value before.
Using a for loop:
public static int power(a, b) { // a ^ b
int p = 1;
for (int i = 1, i <= b; i++)
p *= a;
return p;
}
I have Write a recursive function that accepts two integers. The function returns true if the first number digit amount equal to the second number, otherwise the function returns false.
the function always return true.
What am I doing wrong?
The code:
public static boolean amountEqual(int num1, int num2) {
int sum1 = 0, sum2 = 0;
if (num1 == 0 && num2 == 0 && sum1 == sum2)
return true;
else if (num1 == 0 && num2 == 0 && sum1 != sum2)
return false;
sum1 += num1 % 10;
sum2 += num2 % 10;
return amountEqual(num1 / 10, num2 / 10);
}
thank's
What am I doing wrong?
You are using sum that is always zero. You need to figure out a way to pass your sum1 and sum2 along, so that the final invocation could make a decision based on all prior invocations.
One way of doing it is by making the recursive function with four parameters, and adding a two-parameter overload to start the recursive chain:
public static boolean amountEqual(int num1, int num2) {
return amountEqual(num1, num2, 0, 0);
}
private static boolean amountEqual(int num1, int num2, int sum1, int sum2) {
... // your recursive code goes here
}
Another approach is to compute digit differential, i.e. sum of digits in num1 minus sum of digits in num2, and return true if the differential is zero:
public static boolean amountEqual(int num1, int num2) {
return digitDifferential(num1, num2) == 0;
}
private static int digitDifferential(int num1, int num2) {
return (num1 != 0 || num2 != 0)
? num1%10 - num2%10 + digitDifferential(num1/10, num2/10)
: 0;
}
the first two line of your code every time you call the amountEqual method
it initialize two new variables with zeros
lets trace your recursion
System.out.println(amountEqual(18,26));
/* F(20,30) = F(18/10,26/10) [sum1 = 8 , sum2 = 6]
re init sum1 = 0 , sum2 =0
F(1,2) = F(1/10,2/10) [ sum1 = 1 , sum2 = 2]
re init sum1 = 0 , sum2 = 0
F(0,0) = true */
First of all, your question is unclear. I assumed that you want function to return true if digit sums of both numbers are equal.
Second, you're assuming that numbers are of equal length and they might not be.
Third, you're not passing sum1 and sum2 as paramethers.
Easier approach would be to make two functions, like this:
public static int digitSum(int num) {
if (num > 0) {
return num % 10 + digitSum(num / 10);
}
else
return 0;
}
public static boolean amountEqual(int num1, int num2) {
return digitSum(num1) == digitSum(num2);
}
I can not seem to get my method to convert the binary number to a decimal correctly. I believe i am really close and in fact i want to use a string to hold the binary number to hold it and then re-write my method to just use a .length to get the size but i do not know how to actually do that. Could someone help me figure out how i'd rewrite the code using a string to hold the binary value and then obtain the decimal value using only recursion and no loops?
This is my full code right now and i won't get get rid of asking for the size of the binary and use a string to figure it out myself. Please help :)
package hw_1;
import java.util.Scanner;
public class Hw_1 {
public static void main(String[] args) {
int input;
int size;
Scanner scan = new Scanner(System.in);
System.out.print("Enter decimal integer: ");
input = scan.nextInt();
convert(input);
System.out.println();
System.out.print("Enter binary integer and size : ");
input = scan.nextInt();
size = scan.nextInt();
System.out.println(binaryToDecimal(input, size));
}
public static void convert(int num) {
if (num > 0) {
convert(num / 2);
System.out.print(num % 2 + " ");
}
}
public static int binaryToDecimal(int binary, int size) {
if (binary == 0) {
return 0;
}
return binary % 10
* (int) Math.pow(2, size) + binaryToDecimal((int) binary / 10, size - 1);
}
}
Here is an improved version
package hw_1;
import java.util.Scanner;
public class Hw_1 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter decimal integer : ");
int input = scan.nextInt();
convert(input);
System.out.println();
System.out.print("Enter binary integer : ");
String binInput = scan.next();
System.out.println(binaryToDecimal(binInput));
}
public static void convert(int num) {
if (num>0) {
convert(num/2);
System.out.print(num%2 + " ");
}
}
public static int binaryToDecimal(String binInput){
int len = binInput.length();
if (len == 0) return 0;
String now = binInput.substring(0,1);
String later = binInput.substring(1);
return Integer.parseInt(now) * (int)Math.pow(2, len-1) + binaryToDecimal(later);
}
}
Don't parse binary in reverse order.
Here by calling binaryToDecimal(int) it will return decimal number.
public static int binaryToDecimal(int binary) {
return binaryToDecimal(binary, 0);
}
public static int binaryToDecimal(int binary, int k) {
if (binary == 0) {
return 0;
}
return (int) (binary % 10 * Math.pow(2, k) + binaryToDecimal(binary / 10, k + 1));
}
If you are coding just to convert numbers (not for practice). Then better approach would be to use Integer.parseInt(String, 2). Here you will have to pass binary number in the form of String.
If you are looking to do this using a String to hold the binary representation, you could use the following:
public static int binaryToDecimal(String binaryString) {
int size = binaryString.length();
if (size == 1) {
return Integer.parseInt(binaryString);
} else {
return binaryToDecimal(binaryString.substring(1, size)) + Integer.parseInt(binaryString.substring(0, 1)) * (int) Math.pow(2, size - 1);
}
}
How this works, is with the following logic. If, the number you send it is just 1 character long, or you get to the end of your recursive work, you will return just that number. So for example, 1 in binary is 1 in decimal, so it would return 1. That is what
if (size == 1) {
return Integer.parseInt(binaryString);
}
Does. The second (and more important part) can be broken up into 2 sections. binaryString.substring(1, size) and Integer.parseInt(binaryString.substring(0, 1)) * (int) Math.pow(2, size - 1). The call made in the return statement to
binaryString.substring(1, size)
Is made to pass all but the first number of the binary number back into the function for calculation. So for example, if you had 11001, on the first loop it would chop the first 1 off and call the function again with 1001. The second part, is adding to the total value whatever the value is of the position number at the head of the binary representation.
Integer.parseInt(binaryString.substring(0, 1))
Gets the first number in the current string, and
* (int) Math.pow(2, size - 1)
is saying Multiple that by 2 to the power of x, where x is the position that the number is in. So again with our example of 11001, the first number 1 is in position 4 in the binary representation, so it is adding 1 * 2^4 to the running total.
If you need a method to test this, I verified it working with a simple main method:
public static void main(String args[]) {
String binValue = "11001";
System.out.println(binaryToDecimal(binValue));
}
Hopefully this makes sense to you. Feel free to ask questions if you need more help.
Here is the clean and concise recursive algorithm; however, you'll need to keep track of some global variable for power, and I have defined it as a static member.
static int pow = 0;
public static int binaryToDecimal(int binary) {
if (binary <= 1) {
int tmp = pow;
pow = 0;
return binary * (int) Math.pow(2, tmp);
} else {
return ((binary % 10) * (int) Math.pow(2, pow++)) + binaryToDecimal(binary / 10);
}
}
Note: the reason, why I introduce pow, is that static field needs to be reset.
Just did the necessary changes in your code.
In this way, you would not require the size input from the user.
And,both the conversions of decimal to binary and binary to decimal would be succesfully done.
package hw_1;
import java.util.Scanner;
public class Hw_1 {
public static void main(String[] args) {
int input;
int size;
Scanner scan = new Scanner(System.in);
System.out.print("Enter decimal integer: ");
input = scan.nextInt();
convert(input);
System.out.println();
System.out.print("Enter binary integer : ");
input = scan.nextInt();
System.out.println(binaryToDecimal(input));
}
public static void convert(int num) {
if (num > 0) {
convert(num / 2);
System.out.print(num % 2 + " ");
}
return -1;
}
public static int binaryToDecimal(int binary) {
if(binary==0)
{
return 0;
}
else
{
String n=Integer.toString(binary);
int size=(n.length())-1;
int k=(binary%10)*(int)(Math.pow(2,size));
return k + binaryToDecimal(((int)binary/10));
}
}
}