I try to assign bit wise operators into variables. How can i do it?
Eg
String bitOp="";
String rFunction=JOptionPane.showInputDialog(null,"Enter Your round function","Round function",JOptionPane.INFORMATION_MESSAGE);
if(rFunction.toUpperCase()=="AND")
bitOp="&";
if(rFunction.toUpperCase()=="OR")
bitOp="|";
if(rFunction.toUpperCase()=="XOR")
bitOp="^";
int res= x +bitOp+ y; // if the operator is "AND" , this should be x & y.
//Here NumberFormatException error shows.
System.out.print(res);
But it doesn't work. Anyone please!!!
You could make your own BitOperator:
public enum BitOperator {
AND {
#Override
public int calc(int x, int y) {
return x & y;
}
},
OR {
#Override
public int calc(int x, int y) {
return x | y;
}
},
XOR {
#Override
public int calc(int x, int y) {
return x ^ y;
}
};
public abstract int calc(int x,int y);
}
Usage(add some Exception handling):
String rFunction=JOptionPane.showInputDialog(null,"Enter Your round function","Round function",JOptionPane.INFORMATION_MESSAGE);
System.out.println(BitOperator.valueOf(rFunction.toUpperCase()).calc(x, y));
Your code shouldn't even compile so I am not sure of what you really want to achieve. Do you want to evaluate the String expression you create or do you just want to get the result more classically? Where do x and y come from...? There is an important part of your code that is missing.
Anyway I would chose the second option:
int eval;
String rFunction=JOptionPane.showInputDialog(null,"Enter Your round function","Round function",JOptionPane.INFORMATION_MESSAGE).toUpperCase();
if(rFunction.equals("AND")){
eval = x & y;
} else if(rFunction.equals("OR")){
eval = x | y;
} else if(rFunction.equals("XOR")){
eval = x ^ y;
} else {
//here you could also throw an exception
//or loop and request the user to renew their choice
System.out.print("Invalid choice");
return;
}
System.out.print(res);
Related
In this code a division method is implemented, so i want to handle 3 cases where division is undefined using try catch and throws, but it gives me an error message that the division method must return float .
package calculator3;
//Class implements interface
public class implementation implements calc {
//Add function
public int add(int x, int y) {
int ans1 = x + y ;
return ans1 ;
}
//Divide function
public float divide(int x, int y) throws RuntimeException{
try {
if(y == Double.POSITIVE_INFINITY || y == Double.NEGATIVE_INFINITY || y == 0 ) {
throw new ArithmeticException("invalid_division");
}
else {
return x / y ;
}
}catch (ArithmeticException invalid_division ) {
System.out.println("invalid_division");
}
}
}
Your divide return type is float.
An int will never equal Double.POSITIVE_INFINITY or Double.NEGATIVE_INFINITY because those are not in their range of possible values.
The function will not throw an error if it is caught.
Taking above 3 points:
//divide
public float divide(int x, int y) throws ArithmeticException{
if (y == 0) throw new ArithmeticException("invalid_division");
return (float)x / y; // cast x to float so a float will result
}
Your not actually throwing the exception once catching it so the compiler will complain that your missing a return in your divide() method.
add:
throw e;
to your catch clause
This question already has answers here:
ERROR: This method must return a result of type int
(5 answers)
Closed 4 years ago.
I want to write a Programm which works rekursiv. It shall add two variables. But I am just allowed to add 1 or subtract 1. I made to .Java files. Each of them has one class.
Thats the main class:
package rekursion;
public class Main_function {
public static void main(String[] args) {
// TODO Auto-generated method stub
int a= 5;
int b= 3;
int result = rekursion.Addierer_Multiplizierer.add(a, b);
System.out.print(result);
}
}
and that is the algorithm:
package rekursion;
public class Addierer_Multiplizierer {
public static int add(int x, int y){ // here it Shows an error,
if (x >= 0 && y >= 0){ // because the return value
if(y==0){ // is not of type int
return x;
}
return add(++x, --y);
}
}
}
Your method must have a return value in all of its execution branches.
The question is whether you are supposed to support negative inputs.
If not, you can change your method to:
public static int add(int x, int y)
{
if(y == 0) {
return x;
}
return add(++x, --y);
}
Otherwise, you'll have to check the sign of y, and decide whether to increment or decrement y in order to bring it to 0:
public static int add(int x, int y)
{
if (y == 0) {
return x;
} else if (y > 0) {
return add(++x, --y);
} else {
return add(--x, ++y);
}
}
Or, if you prefer a one liner:
public static int add(int x, int y) {
return y == 0 ? x : y > 0 ? add(++x, --y) : add(--x, ++y);
}
Let me format that a bit for you to make it more clear...
public static int add(int x, int y){
if (x >= 0 && y >= 0){
if(y==0){
return x;
}
return add(++x, --y);
}
// ok, and what if not?
}
Do you see the problem? Inside the first if-block you always return something... But what if (x >= 0 && y >= 0) is not true? No return for that. So you are missing something there.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I must calculate X to the power of Y with recursion and only addition. I really can't figure out how to do it without using loops or using multiplication. This is not my homework. It is a question from last years exams I am stuck on.
import java.util.Scanner;
public class Season4Task7 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter X");
int x = sc.nextInt();
System.out.println("Enter y");
int y = sc.nextInt();
System.out.println(findXY(x, y, 0));
}
static int findXY(int x, int y, int result){
if(y==0){
return 1;
}
if(x==0){
return 0;
}
if(y==1){
return result+x;
}
result+=x;
return findXY(x, y-1, result);
}
}
First two ifs look fine, maybe the 'y-1' as well but after that it might be incorrect, also is there a chance not to use 'int result' but only to pass x and y to the function?
Since we cannot using multiplication, we need to use recursive addition. check my code below. Your first 3 if conditions are correct. Modify the later code to below method.
package com.java;
import java.util.Scanner;
public class Season4Task7 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter X");
int x = sc.nextInt();
System.out.println("Enter y");
int y = sc.nextInt();
System.out.println("Final :: " + findXPowerY(x, y));
sc.close();
}
static int findXPowerY(int x, int y) {
if (y == 0) {
return 1;
}
if (x == 0) {
return 0;
}
if (y == 1) {
return x;
}
return multiply(x, findXPowerY(x, y - 1));
}
static int multiply(int x, int y) {
if (y != 0)
return (x + multiply(x, y - 1));
else
return 0;
}
}
What your findXY method really does is simple multiplication, not exponentiation. First of all, it could be improved from using 3 parameters to only 2:
static int findXY(int x, int y){
if(y==0){
return 1;
}
if(x==0){
return 0;
}
if(y==1){
return x;
}
return x + findXY(x, y-1);
}
Secondly, you are halfway done! You just found a way to multiply with only using addition and recursion. What you now need to do, is call this multiplication certain numer of times, again, using recursion.
Before we start, let's rename the method from findXY to multiply, since it better indicates its intent and functionality.
Thirdly, we need to implement the method that calculates the power. Keeping in mind that we renamed your findXY method to multiply and changed the number of parameters from 3 to 2, our implementation might look like this:
static int power(int x, int y) {
if(y == 0) {
return 1;
}
if(y == 1) {
return x;
}
return x * power(x, y-1));
}
Hey, but we are not allowed to use multiplication! Fortunately, we made our own implementation! The final product looks like this:
static int power(int x, int y) {
if(y == 0) {
return 1;
}
if(y == 1) {
return x;
}
return multiply(x, power(x, y-1));
}
Please do note that this approach does not work with negative numbers. If they are the case, you could wrap this method in another one that simply calls power with abs value and inverts the result
My assignment is to write a recursive function to multiply two numbers together, using only an addition function, ++, and --. My addition function is:
public static int peanoplus(int x, int y) {
if(y==0) return x;
else return peanoplus(++x,--y);
}
What I have so far for my multiplication function is:
public static int peanotimes(int x, int y)
{
if(y==0) return x;
else return peanotimes(peanoplus(x,x),--y);
}
I am not exactly sure what to put in the first parameter for the peanotimes function. Right now the issue is that I'm doubling the number, rather than adding it to the original number. I know that I need to maintain the x variable so that the recursive calls can continue adding the original number (instead of doubling every time), but then where would I actually add the numbers?
I found this which is very similar to my question, but even with those tips I am unable to find a solution.
if( y == 0 || x == 0 ) { return 0; }
else { return peanoplus(x, peanotimes(x,--y)); }
This version closest matches the formal Peano axiom of x * S(y) = x + (x * y)
public static int peanotimes(int x, int y)
{
if (y == 0) {
return 0; // terminate recursion, NB: not "x"
} else {
return peanoplus(x, peanotimes(x, --y));
}
}
In this function I need two different datatype for return, one float when y is not zero and a Boolean when it's zero.
public XXXXX division(int x, int y){
if(y!=0){
return x/y;
}
else{
return false;
}
}
I know that I can implement this with using two function 1- check correction of division 2- calculate the correct division what I want it in One function, It's possible?
Passing 0 as divisor shouldn't be allowed. You should throw an exception instead of returning false in this case:
public float division(int x, int y) {
if (y != 0) {
return ((float) x) / y;
}
else {
throw new IllegalArgumentException("division by 0 makes no sense");
}
}
Not really sure if it is a good practice to have a single method for something like that. But you can create your own class with result and error as property and then return object of that class from your method.
You can check if the value of Y is zero or not before calling the function itself. Don't allow zero to be passed to that function.
And anyway if you pass zero to the function divide by zero situation will throw ArithmaticException. So your function can throw that exception to the caller.
public float division(int x, int y) throws Exception { ///ArithmaticException
return ((float) x) / y;
}
Maybe use a Double as a return type and return the value normally. In case of false, return null.
The simplest way-
public Object division(int x, int y) {
if (y != 0) {
return x / y;
} else {
return false;
}
}
You could return Float, using null signify "no result":
public Float division(int x, int y) {
if(y != 0) {
return x / (float)y;
} else {
return null;
}
}
That said, in this particular case it might actually make sense to return IEEE infinity or NaN.
Note that I've fixed the integer division as it sounds that this isn't what you want.
Maybe you should check it prior:
Pseudocode
if(y!=0){
get division(x/y)
}else{
say Cannot divide by 0
}