Java equality integer - java

I find it kind of confusing, I'm trying to solve this problem I found on the Internet as my programming exercise:
Implement a class with methods which takes one INTEGER parameter "initialValue" and returns following:
a. if initialValue is equal to 1 - return 2 (INTEGER)
b. if initialValue is equal to 2 - return 1 (INTEGER)
This is what I've done so far:
public static void main(String[] args) {
System.out.print(myMethod(1));
}
private static int myMethod(int initialValue) {
int n = 1;
if(initialValue == n) {
return 2;
} else {
return n;
}
}
But I guess this is a basic solution. Do you know any method variations other than this? Thanks.

little fancy solution would be doing XOR with 3
return initialValue ^ 3;

You might use the conditional operator ?: and something like
private static int myMethod(int initialValue) {
return initialValue == 1 ? 2 : 1;
}
The ternary operator is described in the Java Tutorials like
Another conditional operator is ?:, which can be thought of as shorthand for an if-then-else statement (discussed in the Control Flow Statements section of this lesson). This operator is also known as the ternary operator because it uses three operands. In the following example, this operator should be read as: "If someCondition is true, assign the value of value1 to result. Otherwise, assign the value of value2 to result."

I really hope that you plan on using this for learning only not to hand in as your own work. Your way works very well. However, you could also use the modulo operator (assuming of course that the only two inputs would be 1 and 2).
private static int myMethod(int initialValue) {
return initialValue % 2 + 1;
}
Best of luck with your CS aspirations!

public static void main(String[] args) {
int input;
// code for input value
System.out.print(myMethod(input));
}
private static int myMethod(int initialValue) {
int n = 1;
if(initialValue == n) {
return 2;
} else if(initialValue==2) {
return 1;
}
else {
return initialValue;
}
}
This might give better output if you insert values dynamically

It can also be done this way,
private static int myMethod(int initialValue) {
switch (initialValue){
case 1:
return 2;
case 2:
return 1;
default:
return 0;
}
}

Related

The use of relational operator inside binarySearch() method which is a generics is giving error.How to handle this situation?

Here's my java code and the problem is that the use of relational
operator(<) inside binarySearch() is giving error.
I guess this error I am getting because the operands are of type object.
How to remove this error so my function runs perfectly?
import java.util.Random;
import java.util.Arrays;
class BinarySearch
{
public static void main(String $[])
{
Integer arr[]=new Integer[20];
for(int i=0;i<20;i++)
arr[i]=(new Random()).nextInt()%10000;
display("Initial array :\n");
array(arr);
Arrays.sort(arr);
display("After sorting :\n");
array(arr);
display("Enter the element to be searched for : ");
Integer elem=(new java.util.Scanner(System.in)).nextInt();
display(elem+(binarySearch(arr,elem)?" Found":" Not found")+"\n");
}
public static <T>boolean binarySearch(T arr[],T val)
{
int start=0;
int end=arr.length-1;
while(start<=end)
{
int mid=(start+end)/2;
if(arr[mid]==val)
return true;
if(arr[mid]<val)
start=mid+1;
else
end=mid-1;
}
return false;
}
public static void display(Object o)
{
System.out.print(o);
}
public static <T>void array(T arr[])
{
for(int i=0;i<arr.length;i++)
display(arr[i]+" ");
display("\n");
}
}
The problem is that your binarySearch() method is accepting parameters that will be Objects rather than primitive types, so it is unwise to compare them using the equality operator == and invalid to compare them using the less than operator <. Instead define your binarySearch method as follows:
public static <T extends Comparable<T>> boolean binarySearch(T arr[],T val) {
int start = 0;
int end = arr.length-1;
while(start <= end) {
int mid=(start+end)/2;
int comparison = arr[mid].compareTo(val);
if(comparison == 0) {
return true;
}
if(comparison < 0) {
start = mid+1;
}
else {
end = mid-1;
}
}
return false;
}
Read here about generics. Since all generics are objects - you can't use comparison operators with them. Even if you type <T extends Number.
There are two ways to handle this:
Pass Comparator<T> to the method and use comparator.compare(arr[mid], val) for comparing values.
Write <T extends Comparable> and call arr[mid].compareTo(val).
Both these methods return an integer value:
0, if values are equal
negative, if first value less than second
positive, if first value greater than second

Recursion: Binary to Decimal

I am working on a recursive method that takes a binary number as a string and displays its decimal equivalent. I am unsure if my base cases are correct. Also, am I properly imposing recursion within the method?
public static void main(String[] args){
System.out.println("Enter a binary string ");
String binary = input.nextLine();
System.out.println("The decimal equivalent of " + binary + " is "+ binary2Decimal(binary));
}
//MethodOverloading
public static int binary2Decimal(String binary){
return binary2Decimal(binary,0, binary.length()-1);
}
public static void binary2Decimal(String binary, int low, int high){
int temp=0;
if(binary.charAt(high) == 0)
temp *= 2;
else if(binary.charAt(high) == 1)
temp = (temp * 2) + 1;
return binary2Decimal(binary,low,high -1)+temp;
}
}
You don't have a base case; binary2Decimal (3-arg version) always calls itself. (Since the only thing changing from one call to the next is high, your base case should probably involve that somehow.)
Some points:
Your method:
public static void binary2Decimal(String binary, int low, int high)
should have a return type of int instead of void.
You aren't using your variable low (so you can get rid of it if you want).
You need a base case with some code like:
if (high == 0) {
return somevalue;
}
else {
return binary2Decimal(binary,low,high -1)+temp;
}
Otherwise you will get into an infinite loop, and your method will recurse indefinitely.

Given two numbers, return true if any one of them divides the other, else return false

Given two numbers, return true if any one of them divides the other, else return false
public class DividesAB {
static int testcase11 = 208;
static int testcase12 = 7;
boolean aDivisblebyb, bDivisblebya, answer;
public static void main(String args[]){
DividesAB testInstance = new DividesAB();
boolean result = testInstance.divides(testcase11,testcase12);
System.out.println(result);
}
//write your code here
public boolean divides(int a, int b){
boolean aDivisiblebyb = a%b == 0;
boolean bdivisiblebya = b%a == 0;
boolean answer = aDivisiblebyb||bDivisiblebya;
return answer;
}
}
I have been getting errors like cannot find symbol
You have a mess of code thrown together and half it it isn't needed. To find if a symbol is not defined, look at the line of code in your IDE where it is complaining and see why that variable is not in scope.
If you only write the code you need, there is less chance of making a mistake, and it is easier to see where the mistake is.
This is how I would write it
public class DividesAB {
public static void main(String[] args) {
int a = 208, b = 7;
System.out.printf("a: %,d divides b: %,d is %s%n", divides(a, b));
}
//write your code here
public static boolean divides(int a, int b){
return a % b == 0 || b % a == 0;
}
}
The variable names are not correct.
aDivisblebyb and you are using aDivisiblebyb
So change the variable names and it should work.
First, look at the "cannot find symbol" error from your compiler. It should tell you exactly what line the error is occurring on, and most likely the exact error that is occurring. In your case, it will point to:
boolean answer = aDivisiblebyb||bDivisiblebya;
In your declaration, the spelling is different (aDivisblebyb vs aDivisiblebyb), so the compiler does not understand what the symbol aDivisiblebyb is. Same goes for aDivisiblebya. Hence the error.
Side note: you have declared boolean aDivisblebyb and boolean bDivisblebya in two places. In the code you posted, it is unnecessary to access these boolean values outside of the divides method (same with the answer boolean). So, to clean it up a little:
public class DividesAB {
static int testcase11 = 208;
static int testcase12 = 7;
public static void main(String args[]){
DividesAB testInstance = new DividesAB();
boolean result = testInstance.divides(testcase11,testcase12);
System.out.println(result);
}
//write your code here
public boolean divides(int a, int b){
boolean aDivisiblebyb = a%b == 0;
boolean bDivisiblebya = b%a == 0;
boolean answer = aDivisiblebyb||bDivisiblebya;
return answer;
}
}

Correct way to check if a method is invoked recursively

IMPORTANT : THE EXAMPLE IS WRONG, I EXPLAIN WHY AT THE BOTTOM
As the title stated the question is about to define a way to determine when the current executing method is invoked in a recursively way.
I have think about having a "query method" that return a boolean indicating if the invoker method (this is, the method that invokes the "query method") has been already invoked before.
How to check that : just peeking at the stack trace and see if the method we want to check figures two or more times in the stack trace.
Having explaining that, here is the implementation of a method and the respective use of it.
This is not correct...
public class Test
{
public static boolean isRecusivelyInvoqued () {
StackTraceElement[] traces = Thread.currentThread().getStackTrace();
boolean res = false;
// the first belong to "getStackTrace" and the second to "isRecusivelyInvoqued" (this method)
if (traces.length > 2) {
String invokedMethodName = traces[2].getMethodName(); // the third is the method we want to check
for (int i = 3; i < traces.length && !res; i++)
{
res = invokedMethodName.equals(traces[i].getMethodName());
i++;
}
}
return res;
}
// this is a recursive method, used to verify the correct functioning
public static int factorial (int n) {
System.out.println(isRecusivelyInvoqued());
if (n == 0) {
return 1;
}
else {
return n * factorial(n-1);
}
}
public static void main(String[] args)
{
System.out.println(factorial(4));
}
}
I realize if a method in differents namespaces (Class or instance) has the same name, it will return that is invoquedRecursively. I thing that one solution we got this far is that is correct ;) jeje.
This is working for me... is there a better way to archive my goal? How to determine when the current executing method is invoked recursively?
How about this: Your method passes a boolean to the next invocation of the recursive method that tells it that it has been invoked recursively:
public static int factorial (int n) {
return privateFactorial(n, false);
}
private static int privatefactorial(int n, boolean calledRecursively) {
System.out.println(calledRecursively);
if (n == 0) {
return 1;
}
else {
return n * privateFactorial(n-1, true); // tell next invocation here!
}
}
Another option is to add a "is_recursively_invoked" parameter to your recursive function:
public static int factorial (int n, boolean isInvokedRecursively) {
System.out.println(isInvokedRecursively);
if (n == 0) {
return 1;
}
else {
return n * factorial(n-1, true); // these function calls are recursive
}
}
and in your main:
System.out.println(factorial(4, false)); // this function call isn't recursive
If your only goal is to determine if a given method calls itself, then introspect the byte code using any byte code analysis framework and see if there's a call to the method inside the method body.
If you need data about recursion depth then I would use AspectJ (or equivalent) to instrument the method with around advice that can increment a counter. This also eliminates the need for the method itself to do additional work to support your requirement.
That said, I don't understand the need for the requirement; if the method produces the correct answer, and it relies on recursion, then it's using recursion.
You can achieve this using an static boolean variable
Here is a sample:
private static boolean isRecursiveCall = false;
private static int factorial (int n) {
if (n == 0) {
return 1;
}
else {
isRecursiveCall = true;
return n * factorial(n-1);
}
}
public static int findFactorial(int n){
isRecursiveCall = false;
factorial(n);
}
public static void main(String[] args){
findFactorial(2);
}

cheking on symmetric number

How check number on symmetrics?
public static int Symmetric(int a) {
if(new StringBuilder(Integer.toString(a)) ==
new StringBuilder(Integer.toString(a)).reverse())
return a;
else
return 0;
}
I try do it smth like this but always return 0.
You can't use == to compare Strings (or StringBuilders), you need to use equals().
Also, you need to turn the StringBuilders back to Strings before comparing:
EDIT:
Also, there is really no need for the first StringBuilder:
public static int symmetric(int a) {
if (Integer.toString(a).equals(new StringBuilder(Integer.toString(a)).reverse().toString()))
return a;
else
return 0;
}
Equality is explained here in JLS.
You must use equals() on Strings: StringBuilder.toString().equals().
public static int Symmetric( int a ) {
return
new StringBuilder(Integer.toString(a)).toString().equals(
StringBuilder(Integer.toString(a)).reverse().toString())
? a : 0;
}

Categories

Resources