简体   繁体   中英

Return types and Methods in java

Can you guys help me fix the following program?

It is giving me the following error:

error: method absoluteValue in class Pset3Ex4 cannot be applied to given types;

import java.util.Scanner;

public class Pset3Ex4 {

    public static void main(String[] args) {
        absoluteValue();
    }

    public double absoluteValue(double d) {
        Scanner sc = new Scanner(System.in);

        System.out.print("Input a number: ");
        d = sc.nextDouble();

        if (d < 0) {
            return -d;
        } else {
            return d;
        }
    }
}

You are calling method

 absoluteValue() 

without any argument, while you have defined a method with a double argument

absoluteValue(double d), 

So java compiler did not find the method

absoluteValue() 

without argument.

Second, you are trying to call a non-static method from the static main method which is not permitted.

Your absoluteValue(double d) is neither static and does not take zero arguments. Therefore you will get an error when you try to compile this.

To fix that, just change the signature and modifiers for absoluteValue :

public static double absoluteValue() {
    double d;
    ...

First, you need to pass an argument to that function (a double argument!) Second, this function need to be static, it is a part of a class that has not been instanced yet. If you make a new instance, meaning :

 Pset3Ex4 p = new Pset3Ex4();

You'll be able to call the function from p (the new instance). Otherwise, you'll have to make this method static, it will allow you to access it without having to make new instance of it.

  1. Ths signature of the function is absoluteValue(double d) so it requires an double as parameter, but you call it like absoluteValue(); without. You need to set you function signature to

     public double absoluteValue(double d){ //... } 
  2. Your function is not static, it requires a instance to be called, so :

    • use an instance

       public static void main(String[] args){ new Pset3Ex4().absoluteValue(); } 
    • make it static

       public static double absoluteValue(double d){ //... } 

Check if this what you are looking at. Method 'absoluteValue' is not static and you are not passing any argument when you are are calling the method in main.

import java.util.Scanner;

public class Pset3Ex4 {

public static void main(String[] args){
System.out.print("Result is " + absoluteValue());
}

public static double absoluteValue(){
Scanner sc = new Scanner(System.in);

System.out.print("Input a number: ");
d = sc.nextDouble();

if (d < 0){
return - d; 
}
else {
return d;
}

}  
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM