Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I just learned how to use classes and constructors but Idk why my code isn't running. Said illegal start, but I'm positive that it is right. I also looked at other people's code and they are the same as what I put. Can someone look at what is wrong
public class Calculator{//basic calculator
public Calculator(){
public int add(int a, int b){
return a+b;
}
public int subtract(int a, int b){
return a-b;
}
public int multiply(int a, int b){
return a*b;
}
public int divide(int a, int b){
if(b==0){
System.out.println("Error! Dividing by zero is not allowed.");
return 0;
}else{
return a/b;
}
}
public int modulo(int a, int b){
if(b==0){
System.out.println("Error! Dividing by zero is not allowed.");
return 0;
}else{
return a%b;
}
}
}
public static void main(String[]args) {
Calculator myCalculator = new Calculator();
System.out.println(myCalculator.add(5, 7));
System.out.println(myCalculator.subtract(12, 34));
}
}
Remove public Calculator() { that line does nothing.
EDIT: Actually at second glance it looks like that line was an attempted constructor but you wrapped the entire classes contents in the brackets {}. This should work:
public class Calculator {//basic calculator
public Calculator() {
}
public static void main(String[] args) {
Calculator myCalculator = new Calculator();
System.out.println(myCalculator.add(5, 7));
System.out.println(myCalculator.subtract(12, 34));
}
public int add(int a, int b) {
return a + b;
}
public int subtract(int a, int b) {
return a - b;
}
public int multiply(int a, int b) {
return a * b;
}
public int divide(int a, int b) {
if (b == 0) {
System.out.println("Error! Dividing by zero is not allowed.");
return 0;
} else {
return a / b;
}
}
public int modulo(int a, int b) {
if (b == 0) {
System.out.println("Error! Dividing by zero is not allowed.");
return 0;
} else {
return a % b;
}
}
}
EDIT #2: As Wombat pointed out (one of my least favorite Java features because of how much time I've spent troubleshooting) is that a / b is integer division and will (practically) never give you the result you need. Also, your method returns int which was probably not your intention. So your divide method should use double:
public double divide(double a, double b) {
if (b == 0) {
System.out.println("Error! Dividing by zero is not allowed.");
return 0;
} else {
return a / b;
}
}
Related
I want to ask a question how to create a "Division" function which contains variable number of parameters in Java? Just Like As I did for sum method:
public static int sum(int ... x)
{
int sum=0;
for(int i : x)
{
sum=sum+i;
}
return sum;
}
Well, the difference is that you're gonna have to provide a number to divide as parameter:
public static int div(int div, int ... x)
{
for(int i : x)
{
if(i > 0) div=div/i;
}
return div;
}
Be careful to test if i is greater than 0, otherwise the compiler will throw an error, since you cannot divide by 0.
I have a recursive method that computes x^n with a certain algorithm, but this is of no importance here. What matters is my helper function which keeps track of recursive calls of this algorithm.
public class FastPot {
public static double fastPotRek(double x, int n) {
class Aux {
private double aux(double x, int n, int c) {
if (n == 0) {System.out.print("It took "+c+" recursive calls to compute "); return 1;}
else return (n % 2 == 0) ? aux(x*x, n/2, c+1)
: x * aux(x, n-1, c+1);
}
}
Aux a = new Aux();
return a.aux(x, n, 0);
}
}
To organize that somewhat I wanted to declare aux inside fastPotRek, and for that you have to use an inner class, whose methods I can't declare static. Because of this I instantiate Aux a = new Aux(); to be able to call aux.
Please tell me there is a way to make this more elegant and show me what I have overlooked... Like beeing able to make aux static somehow or not needing to instantiate Aux.
No need for inner class and no need to make that static as well:
public class FastPot {
//Static, use only from within FastPot
private static double aux(double x, int n, int c) {
if (n == 0) {
System.out.print("It took "+c+" recursive calls to compute ");
return 1;
} else {
return (n % 2 == 0) ? aux(x*x, n/2, c+1)
: x * aux(x, n-1, c+1);
}
}
}
//Your outward interface
public static double fastPotRek(double x, int n) {
return aux(x, n, 0);
}
}
Or if you insist on using an inner class:
public class FastPot {
//Static, use only from within FastPot
private static class Aux {
private static double aux(double x, int n, int c) {
if (n == 0) {
System.out.print("It took "+c+" recursive calls to compute ");
return 1;
} else {
return (n % 2 == 0) ? aux(x*x, n/2, c+1)
: x * aux(x, n-1, c+1);
}
}
}
//Your outward interface
public static double fastPotRek(double x, int n) {
return Aux.aux(x, n, 0);
}
}
I'll post this answer although many people (including me) will not be happy with this. Please don't use this kind of code:
public static double fastPotRek(double x, int n) {
return new Cloneable() {
private double aux(double x, int n, int c) {
if (n == 0) {System.out.print("It took "+c+" recursive calls to compute "); return 1;}
else return (n % 2 == 0) ? aux(x*x, n/2, c+1) : x * aux(x, n-1, c+1);
}
}.aux(x, n, 0);
}
Again, i highly suggest to use a private static method like:
public static double fastPotRek(double x, int n) {
return aux(x,n,0);
}
private static double aux(double x, int n, int c) {
...
}
You have this:
Aux a = new Aux();
return a.aux(x, n, 0);
I would write it like this (Does the same):
return new Aux().aux(x, n, 0);
Edit: I´m done with StackOverflow. You guys don´t want help? I won´t give it. From now on, I will only ask about MY problems, and won´t answer.
I'm creating a method to add up all numbers between two integers.
I currently have:
/**
* Add up all numbers between two integers
*/
public void Sum(int a,int b)
{
int result = 0;
while (a <=b)
{
result+=a;
a++;
}
System.out.println("The sum of all numbers is "+result);
}
This only works if a <= b. How do i also do it for if a > b ?
I have to use a while loop
The easiest way to do this is to reuse what you already have. Let's rename your method first:
public void sumMonotonic(int a, int b)
{
int result = 0;
while (a <=b) {
result+=a;
a++;
}
System.out.println("The sum of all numbers is "+result);
}
So sumMonotonic() only works if its first argument is no bigger than its second. But now we can define sum() like this:
public void sum(int a, int b)
{
if (a<=b)
sumMonotonic(a,b);
else
sumMonotonic(b,a);
}
This just invokes the other function with the arguments in the appropriate order.
Actually there's one other oddity that we might fix. It seems a little unidiomatic to have a sumMonotonic() method that does the printing. It would be better if it returned the sum, and if the sum() method did the printing. So we'd refactor it like this:
public int sumMonotonic(int a, int b)
{
int result = 0;
while (a <=b) {
result+=a;
a++;
}
return result;
}
public void sum(int a, int b)
{
int result;
if (a<=b)
result = sumMonotonic(a,b);
else
result = sumMonotonic(b,a);
System.out.println("The sum of all numbers is "+result);
}
public void Sum(int a,int b)
{
int result = 0;
if(a>b) //swap them
{
result=a;
a=b;
b=result;
result=0;
}
while (a <=b) {
result+=a;
a++;
}
System.out.println("The sum of all numbers is "+result);
}
I've been trying to write a simple function in Java that can calculate a number to the nth power without using loops.
I then found the Math.pow(a, b) class... or method still can't distinguish the two am not so good with theory. So i wrote this..
public static void main(String[] args) {
int a = 2;
int b = 31;
System.out.println(Math.pow(a, b));
}
Then i wanted to make my own Math.pow without using loops i wanted it to look more simple than loops, like using some type of Repeat I made a lot of research till i came across the commons-lang3 package i tried using StringUtils.repeat
So far I think this is the Syntax:-
public static String repeat(String str, int repeat)
StringUtils.repeat("ab", 2);
The problem i've been facing the past 24hrs or more is that StringUtils.repeat(String str, int 2); repeats strings not out puts or numbers or calculations.
Is there anything i can do to overcome this or is there any other better approach to creating a function that calculates powers?
without using loops or Math.pow
This might be funny but it took me while to figure out that StringUtils.repeat only repeats strings this is how i tried to overcome it. incase it helps
public static int repeat(int cal, int repeat){
cal = 2+2;
int result = StringUtils.repeat(cal,2);
return result;
}
can i not use recursion maybe some thing like this
public static RepeatThis(String a)
{
System.out.println(a);
RepeatThis(a);
}
just trying to understand java in dept thanks for all your comments even if there were syntax errors as long as the logic was understood that was good for me :)
Another implementation with O(Log(n)) complexity
public static long pow(long base, long exp){
if(exp ==0){
return 1;
}
if(exp ==1){
return base;
}
if(exp % 2 == 0){
long half = pow(base, exp/2);
return half * half;
}else{
long half = pow(base, (exp -1)/2);
return base * half * half;
}
}
Try with recursion:
int pow(int base, int power){
if(power == 0) return 1;
return base * pow(base, --power);
}
Function to handle +/- exponents with O(log(n)) complexity.
double power(double x, int n){
if(n==0)
return 1;
if(n<0){
x = 1.0/x;
n = -n;
}
double ret = power(x,n/2);
ret = ret * ret;
if(n%2!=0)
ret = ret * x;
return ret;
}
This one handles negative exponential:
public static double pow(double base, int e) {
int inc;
if(e <= 0) {
base = 1.0 / base;
inc = 1;
}
else {
inc = -1;
}
return doPow(base, e, inc);
}
private static double doPow(double base, int e, int inc) {
if(e == 0) {
return 1;
}
return base * doPow(base, e + inc, inc);
}
I think in Production recursion just does not provide high end performance.
double power(double num, int exponent)
{
double value=1;
int Originalexpn=exponent;
double OriginalNumber=num;
if(exponent==0)
return value;
if(exponent<0)
{
num=1/num;
exponent=abs(exponent);
}
while(exponent>0)
{
value*=num;
--exponent;
}
cout << OriginalNumber << " Raised to " << Originalexpn << " is " << value << endl;
return value;
}
Use this code.
public int mypow(int a, int e){
if(e == 1) return a;
return a * mypow(a,e-1);
}
Sure, create your own recursive function:
public static int repeat(int base, int exp) {
if (exp == 1) {
return base;
}
return base * repeat(base, exp - 1);
}
Math.pow(a, b)
Math is the class, pow is the method, a and b are the parameters.
Here is a O(log(n)) code that calculates the power of a number. Algorithmic technique used is divide and conquer. It also accepts negative powers i.e., x^(-y)
import java.util.Scanner;
public class PowerOfANumber{
public static void main(String args[]){
float result=0, base;
int power;
PowerOfANumber calcPower = new PowerOfANumber();
/* Get the user input for the base and power */
Scanner input = new Scanner(System.in);
System.out.println("Enter the base");
base=input.nextFloat();
System.out.println("Enter the power");
power=input.nextInt();
result = calcPower.calculatePower(base,power);
System.out.println(base + "^" + power + " is " +result);
}
private float calculatePower(float x, int y){
float temporary;
/* Termination condition for recursion */
if(y==0)
return 1;
temporary=calculatePower(x,y/2);
/* Check if the power is even */
if(y%2==0)
return (temporary * temporary);
else{
if(y>0)
return (x * temporary * temporary);
else
return (temporary*temporary)/x;
}
}
}
Remembering the definition of the logarithm, this can be done with ln and exp if these functions are allowed. Works for any positive base and any real exponent (not necessarily integer):
x = 6.7^4.4
ln(x) = 4.4 * ln(6.7) = about 8.36
x = exp(8.36) = about 4312.5
You can read more here and also here. Java provides both ln and exp.
A recursive method would be the easiest for this :
int power(int base, int exp) {
if (exp != 1) {
return (base * power(base, exp - 1));
} else {
return base;
}
}
where base is the number and exp is the exponenet
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;
}
}