math.pow in method results to an error - java

could anyone please explain why the following method doesn't work and returns the following error message: "Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - Erroneous tree type: "
class Example01 {
public static void main(String[] args) {
System.out.println(myExp(2));
}
double myExp(int x) {
return Math.pow(x,2);
}
}
I thought it might be for using int variable in Math.pow but I tried it this way without setting up a method and it worked ok:
System.out.println(Math.pow(2,2));
Could someone please give a bit of a flavour on why the method fails to return the result?
Many thanks,
Vlad

change the method double myExp(int x) to static double myExp(int x).

method double myExp(int x) should be static.

You have to declare myExp static.
static double myExp(int x) {
return Math.pow(x,2);
}
or you can instantiate a Example01 class and call the function.
class Example01 {
public static void main(String[] args) {
Example01 ex = new Example01();
System.out.println(ex.myExp(2));
}
double myExp(int x) {
return Math.pow(x,2);
}
}

In java all the non-static method are instance method i.e. they require an instance or an object to be called upon.Either declare your myExp(int x) method static i.e. static double myExp(int x) or instantiate your class to create an object and then call myExp(int x) on it i.e.
class Example01 {
public static void main(String[] args) {
Example01 example = new Example01();
System.out.println(example.myExp(2));
}
double myExp(int x) {
return Math.pow(x,2);
}
}

Related

I cant access a class I defined from the main loop?

I have an extremely simple piece of code where I am calling a method that I defined, and it wont run because it says I haven't defined the method?
class Main {
public static void main(String[] args) {
go(7,3);
}
}
/// in a separate file named go.java -->
class go{
public static int go(int x, int y){
if(x <= 1)
return y;
else
return go(x - 1, y) + y;
}
}
You have two options, use the class name go to identify the class containing the method
public static void main(String[] args) {
go.go(7,3);
}
or static import it like
import static go.go;
public class Main {
public static void main(String[] args) {
go(7,3);
}
}
First thing first, Class name should start with upper case, your another class should be Go.java , to access static method
Refer Class name that is Go.go(7,3);

How do I call a method that has a variable passed through it?

I'm trying to call a method from within another method. I'm understanding this simply enough, until one of those methods needs a variable carried through, and then nothing I try works.
I know that I could do this in one method, but my coursework needs me to lay it out in such a way. Why doesn't this work?
public class test2 {
public static void testMethod() {
int randomNumber = 1;
}
public static void anotherTestMethod(int randomNumber) {
System.out.println(randomNumber);
}
public static void main(String[] args) {
anotherTestMethod();
}
}
You are calling a method that has an int parameter in its signature. You should pass that parameter when calling the method. I think you are trying to use a global variable, in that case, you should declare it outside any method, as a part of the class.
public class test2 {
public static int testMethod() {
int randomNumber = 1;
return randomNumber;
}
public static void anotherTestMethod() {
System.out.println(testMethod());
}
public static void main(String[] args) {
anotherTestMethod();
}
}

Can’t figure out how to Return a value

This will probably will get down voted, so if you do down vote me, can you provided a link to where I can find this?
What am I doing wrong here? I am very new and it seems like this should work. I just don't know what I am doing wrong. This is my error
public class Test
{
public static long calculate(long n)
{
n = args[0];
return n;
}
public static void main(String[] args)
{
long answer;
answer = calculate();
}
}
Exception:
Test.java:6: error: cannot find symbol
n = args[0];
^
symbol: variable args
location: class Test
Test.java:13: error: method calculate in class Test cannot be applied to given types;
answer = calculate() ;
^
required: long
found: no arguments
reason: actual and formal argument lists differ in length
2 errors
args is a String array local to the main method.
So firstly it is a local variable of the main method and it is not visible inside the calculate method which explains the first error: error: cannot find symbol.
Secondly calculate expects a long parameter and your are trying to supply a String. For that you are getting error: method calculate in class Test cannot be applied to given types;
So pass args[0] to the calculate after converting it to long as a parameter.
public class Test
{
public static long calculate(long n)
{
return n;
}
public static void main(String[] args)
{
long answer = 0L;
try{
answer = calculate(Long.parseLong(args[0]));
}catch (ArrayIndexOutOfBoundsException ae){
ae.printStackTrace();
}catch (NumberFormatException nfe){
nfe.printStackTrace();
}
System.out.println(answer);
}
}
In whole class there is no instance variable defined with named args, variable which you are trying to use is a parameter in main method and accessible only inside main method.
By considering your code your doing nothing inside calculate so you can write main method as follows:
public static void main(String[] args)
{
long answer;
answer = Long.parseLong(args[0]);
}
Both code will do same work.
Below code can solve your issue
public class Test
{
public static long calculate(String[] args)
{
long n = Long.parseLong(args[0]);
return n;
}
public static void main(String[] args)
{
long answer;
answer = calculate(args);
}
}

Why is there an error in the following java code?

I can't figure out the problem in this.
public class Trying {
public static void main(String[] args) {
new Trying().go("hi", 1);
new Trying().go("hi", "world", 2);
}
public void go(String... y, int x) {
System.out.print(y[y.length - 1] + " ");
}
}
A varargs argument, like String... y has to be the last variable in a method declaration. Change your declaration to:
public void go(int x, String... y) {
A varargs argument must be the last variable in a method declaration
public class Trying {
public static void main(String[] args) {
new Trying().go(1,"hi");
new Trying().go(2,"hi", "world");
}
public void go(int x,String... y) {
for(int i=0;i<x;i++){
System.out.println(y[i]);
}
}
}
For More
There is an attempt to declare Regular parameter after the varargs parameter which is illegal.
public void go(String... y, int x) //Error
Restriction of varags:
varargs must be declared last
2.There must be only one varargs parameter
change your method to public void go(int x, String... y)

Java Overloading: Number,Number ; int,Double

In two days i have an exam in java, and i can not figure out the answer to this question:
class ClassA {
public String foo(Integer x , int y) {
return "Integer, int";
}
public String foo(int x, Double y) {
return "int, Double";
}
public String foo(Number x, Number y) {
return "Number, Number";
}
public String foo(Object x, Object y) {
return "Object, Object";
}
public static void main(String... args) {
ClassA a = new ClassA();
System.out.print(a.foo(5, 1.2f) + " ");
System.out.println(a.foo(null, null));
}
}
What's the output?
The Answer is:
Number, Number Number, Number
I know that java always chooses the most specified Method, that is why a.foo(null,null); will envoke the Number,Number Method and not the Object,Object Method.
But why does a.foo(5,1.2f); also envoke the Number,Number Method and not the int,Double Method??
But one more thing which might be helpful:
If i remove the f after 1.2, so that the call is:
a.foo(5,1.2);
I get a compiler error, that it can not choose between the Number,Number and int,Double Method...
Would be really helpful, if you guys could explain that to me :)
1.2f is not wrapped by a Double, it's wrapped by a Float. SinceFloat is not a subclass of Double (they are distinct subclasses of Number), the most specific method signature that can be used is foo(Number,Number).
Once you remove the f, 1.2 will be treated a double (the primitive, not the wrapper class) by default, which can be autoboxed to a Double. However the 5 can also be autoboxed to an Integer, thus causing the ambiguity.
There are two important factors here.
First, 1.2f is not a Double. It's a Float. The (int, Double) function doesn't match at all. (Number, Number) is the best fit.
Second, even when you change it to 1.2 it is still not a Double. It is a double. That is, it's a primitive, not an object. Now, Java will still happily pass a double into a function that wants a Double without much complaint, but in this case you've confused it by giving it two valid conversions it could make:
Convert 5 to an Integer and convert 1.2 to a Double
Leave 5 as a primitive int but convert 1.2 to a Double.
There isn't a rule for which of those is preferable. Java produces a compiler error that it has an ambiguous function call, and forces you to choose which one you'd prefer (by manually wrapping one or both of them in objects).
As an aside, if you had a method that took (int, double) there would be no ambiguity at all: that method actually matches the existing types of 5 and 1.2, so it would be called. It's the fact that some of the arguments here are wrapper objects that causes the mayhem.
Generic Answer:
public class OverloadingNumeric {
public void print(int x){
System.out.println("int");
}
public void print(long x){
System.out.println("long");
}
public void print(float x){
System.out.println("float");
}
public void print(double x){
System.out.println("double");
}
public void print(Integer x){
System.out.println("Integer");
}
public void print(Long x){
System.out.println("Long");
}
public void print(Float x){
System.out.println("Float");
}
public void print(Double x){
System.out.println("Double");
}
public void print(Number x){
System.out.println("Double");
}
public void print(Object x){
System.out.println("Object");
}
public static void main(String[] args) {
OverloadingNumeric obj = new OverloadingNumeric();
/*
* Primitives will take more precedence
* of calling instead of wrapper class arguments,
*/
obj.print(10);
obj.print(10l);
obj.print(10f);
obj.print(10d);
obj.print(10.1);
//obj.print(999999999999999); Error: this letral type int is out of range
obj.print(999999999999999l);
/*
* OUTPUT
* int
* long
* float
* double
* double
* long
*/
/*
* Assume all primitive argument methods
* are commented. then calling the same again
*/
obj.print(10);
obj.print(10l);
obj.print(10f);
obj.print(10d);
obj.print(10.1);
//obj.print((Double)10); //Cannot cast int to Double
obj.print((double)10); //Success
//obj.print((Float)10); //Cannot cast int to Float
obj.print((float)10); //Success
//obj.print(null); ERROR AMBIGUOUS
/*
* OUTPUT
* Integer
* Long
* Float
* Double
* Double
* Double
* Float
*
*/
}
}
interface SuperIfc {}
class SuperClass implements SuperIfc{}
class SubClass extends SuperClass {}
public class OverloadingTest {
public void print(SuperIfc x){
System.out.println("SuperIfc");
}
public void print(SuperClass x){
System.out.println("SuperClass");
}
public void print(SubClass x){
System.out.println("SubClass");
}
public void print(Object x){
System.out.println("Object");
}
public static void main(String[] args) {
OverloadingTest obj = new OverloadingTest();
SuperClass superObj = new SuperClass();
SubClass subObj = new SubClass();
obj.print(superObj);
obj.print(subObj);
obj.print(null);
obj.print((SuperIfc)superObj);
obj.print((SuperIfc)subObj);
obj.print((SuperIfc)null);
/*
* OUTPUT
* SuperClass
* SubClass
* SubClass
* SuperIfc
* SuperIfc
* SuperIfc
*/
}
}

Categories

Resources