My 1st attempt with method in Java: doesn't work - java

I need to put this (Math.random() * 37) into a working method.
This is what I made with a tutorial but there is an error on the first row "identifier expected". What is wrong with this code? Please help.
public static double hodKulickou (double)
{
return (Math.random() * 37);
}

You almost got it right. You should consider understanding the principles behind your methods declaration.
In your case you did not provide a local name for the method to assign to the double value it was expecting. Read on if you're interested in understanding the principles as I understand them.
Each word in the method declaration serves a purpose. From left to right.
public - means this method can be accessed publicly and not just by code in that class.
static - means the methods is static and belongs to that class, is not a object member.
void - means the methods does not return any value.
yourmethod name - any name you see fit.
Now the interesting part. The method parameters. These are the values you may pass into the method. In the paramaters you include the type and a name for the value.
eg: methodName(int anInteger)
This means the method can expect an integer type to be passed to is and the method will call that integer anInteger for use within it's body. For whatever purpose you see fit.

You have to give a name to the double parameter of your method.
public static double hodKulickou (double name) {
return (Math.random() * 37);
}
Of course, since you are not using the double parameter, you can just remove it :
public static double hodKulickou () {
return (Math.random() * 37);
}

Did you really followed the instructions of the tutorial ? You must provid an identifier to your parameters. That's exactly what the error message tells you btw.
public static double hodKulickou (double identifier) {
return (Math.random() * 37);
}
However, you pass a parameter to your function but don't use it so actually it should be :
public static double hodKulickou () {
return (Math.random() * 37);
}

Also, since you don't use the parameter, you can omit it:
public static double hodKulickou () { // <-- skipped
return (Math.random() * 37);
}

Your method doesn't appear to need a parameter, this
public static double hodKulickou (double)
should be
public static double hodKulickou ()
or
public static double hodKulickou (int val) { return (Math.random() * val); }
if you want to pass the "37" in.

Related

Why am I getting the error "cannot resolve method "x" in "x""?

The purpose of this program is to create a class and tester class for a select object(in my case a monitor), with at least one overloaded method. And in the client class, I have to instantiate at least three instances of the object. So far I believe I've finished the first class with the declaration of methods, getters and setters, and constructors. The problem occurs in my tester class, where I get the error "Cannot resolve method 'MonitorV82' in 'Monitor V82'. I don't know for sure why I'm getting this error, any advice?
My first class is:
public class MonitorV82
{
private double l;
private double h;
//one parameter constructor, all private instance variables initialized
public MonitorV82(double monitor1Height) {
//2.When this gets name1(jupiter), it designates "jupiter" to the variable "n"
h = monitor1Height;
l = (monitor1Height * 1.77);
}
//two parameter constructor
public MonitorV82(double monitor1Height, double monitor1Length){
//3.When this gets name1(jupiter), and a double, it sets jupiter to "n" and the diameter to "d"
h = monitor1Height;
l = monitor1Length;
}
public double getMon1height() { return h; }
public double getMon1Length() {
return l;
}
public void setMon1height(double name) { h = name; }
public void setMon1Length(double diam) {
l = diam;
}
public String monType(int resolution)
{
String monitType = "";
if (resolution == 1080) {
monitType = "lenovo";
} else if (resolution == 4000) {
monitType = "samsung";
}
return monitType;
}
//overloaded method
public String monType(int pixLength,int pixHeight)
{
String monitType = "";
if (pixHeight == 1080) {
monitType = "lenovo";
} else if (pixHeight == 4000) {
monitType = "samsung";
}
return monitType;
}
}
My tester class(where the error is) is:
public class V8Tester {
public static void main(String[] args) {
double length1 = 32.2;
double height1 = 51.8;
double length2 = 31.8;
double height2 = 50.6;
int resolution = 0;
MonitorV82 monit1 = new MonitorV82(length1);
resolution = monit1.MonitorV82(height1);
}
}
I am still learning Java in school so please don't roast me if something seems obvious or simple. Thank you for your help.
You are getting this error because there is no method MonitorV82, only a constructor. Also you are trying to instantiate the int variable resolution with a MonitorV82 object, which is not possible, because the compiler expects an int value.
If you want the resolution that refers to the pixel count of the MonitorV82 object with known pixel height, you first need to find out it's pixel length. You can do this by using your getMon1length() method and the calculate the resolution by length * height. Ultimately what I think you are trying to do is:
int heightMonit1 = monit1.getMon1height();
int resolution = (int)length1 * (int)heightMonit1;
You need to type cast, because you want to instantiate the int variable resolution with a calculation of double values.
You could however also use your second constructor and do:
MonitorV82 monit1 = new MonitorV82(length1, height1);
int resolution = (int)monit1.getMon1height() * (int)monit1.getMon1length();
Before answering the question in the title, you need the answer to this question:
What is a constructor in Java?
A constructor in Java is a special method used to "construct" (build, instantiate, etc.) objects. A constructor follows these basic rules:
The name of the constructor should match exactly the class name. In your case, MonitorV82 is this name.
A constructor doesn't have a return type. The new operator is responsible for returning a new object matching the type of the class in which the constructor is being invoked.
Knowing this, let's address the original question: Why the error? Because in MonitorV82 there is only a constructor a with matching name, but not a regular method with the same name. Consider my example below
public class Test {
private String name = "default";
// constructor #1
public Test() {}
// constructor #2
public Test(String name) {
this.name = name;
}
// method #1
public void Test() {
System.out.println(name);
}
// method #2
public void Test(String name) {
System.out.println(name);
}
}
Notice that in the code above, I have two constructors and two methods with the same name (matching case) and same parameters. This is allowed in Java although this is STRONGLY discouraged due to how confusing it can get.
What does this mean for you?
To create monit1, you need to invoke a CONSTRUCTOR. Once you construct the object, you cannot use it to invoke a constructor. You use objects to invoke non-static, accessible methods. Based on this, the line
MonitorV82 monit1 = new MonitorV82(length1);
is totally fine. However, the set resolution line is not resolution = monit1.MonitorV82(height1); because you have no METHOD named MonitorV82 (you just have a constructor with a matching name). You fix this by creating a method in your class that does exactly that. Since method names should be descriptive of their function, creating a method named setResolution or calculateResolution should be fine. What you should not do is used an ambiguous name; especially using the same name as the constructor.
Lastly, I will leave you with this small piece of advice: Just because the language allows you to do something, that does not mean that it is correct or OK to do so. My code example (along with this lengthy explanation) should've illustrated this point.
tl;dr
You asked:
Why am I getting the error "cannot resolve method "x" in "x""?
Because your last line tries to call a method named MethodV82 which does not exist on an instance of the class named MethodV82.
Details
Firstly, you should have indicated which line of code is causing that error.
You have at least one offending line, that last line. The code monit1.MonitorV82(height1) makes no sense. That code is trying to call a method named MonitorV82 on the instance named monit1. But of course there is no such method. Thus the error « Cannot resolve method ».
I cannot follow your logic, so I cannot give a fixed replacement code snippet.
I think you are misunderstanding the use of constructors.
I guess that what you want to do with your monit1.MonitorV82(height1) is to set the height of your monit1 instance to height1.
You need to call the setter to do so, not a constructor. The constructor is not known as a class method, that is why your error occurs. Use
monit1.setMon1height(height1);
Next, I think that you are trying to retrieve a resolution from your monitor, but you have no method inside of your MonitorV82 with this aim so I suggest that you create a method for this such as
public int computeResolution() {
return this.h * this.l;
}
In your test class you end up with:
public class V8Tester {
public static void main(String[] args) {
double length1 = 32.2;
double height1 = 51.8;
double length2 = 31.8;
double height2 = 50.6;
int resolution = 0;
MonitorV82 monit1 = new MonitorV82(length1);
monit1.setMon1height(height1);
resolution = monit1.computeResolution();
}
}
Edit: Even the instantiation of your monit1 does not seem correct. The only one parameter constructor you have is based on height and you are calling it with length1
Edit2: My example of computeResolution() will probably end up with an exception as I am returning an int from a compute action on doubles. But I think that it is not the main issue here

How to set up overload method to find circumference of a circle?

I'm just learning the ropes of overloaded methods. Here is an assignment in which I have to write the overloaded methods in the incomplete CircleStats class, but I have no idea how to set them up. I am supposed to find the circumference of a circle using its diameter/radius.
I understand that I have to make functions for finding circumference using the diameter, then using the radius, but don't know where to go from there. I also know that the radius will be double and the radius will be int, but am completely ousted with how to fill in the //code goes here part.
It would also be wonderful if someone could explain how to set up the math in each overload method to calculate circumference.Thanks in advance!
EDIT: In lines 21 and 22, it should be cStats.calcCircleCircumf instead of cStats.calcCircleArea
/* The calcCircleCircumf( ) method in the CircleStatsTester class is overloaded. Write the overloaded methods in the incomplete CircleStats class.*/
class CircleStats
{
CircleStats()
{
}
//…code goes here
}
public class CircleStatsTester
{
public static void main(String[] args)
{
int diameter = 5;
double radius = 2.5;
CircleStats cStats = new CircleStats();
System.out.println("The area = " + cStats.calcCircleArea(diameter));
System.out.println("The area = " + cStats.calcCircleArea(radius));
}
}
That is basically impossible.
Overloading a method consists in having two methods with the same name, but with a different signature (i.e. with a different number of arguments and/or arguments of different types).
Since a radius and a diameter have the same type, Java has no way to distinguish
calcCircleCircumf(double radius)
from
calcCircleCircumf(double diameter)
So you need two methods with different names:
computeCircumferenceFromRadius(double radius)
computeCircumferenceFromDiameter(double diameter)
and this is not overloading anymore.
Note about naming: these methods are part of a class named CircleStats. So puttin "Circle" in the method name is redundant and only adds noise. Using complete words makes the code more readable though, and that's the convention in Java. Hence computeCircumferenceFromRadiusand not calcCircleCircumf.
Even though this looks odd to me, but I think this is what you are asking.
public int calcCircleCircumf(int radius)
{
return (int)(2 * Math.PI * radius);
}
public double calcCircleCircumf(double diameter) //method overloading
{
return (2 * Math.PI * (diameter/2));
}
I think this is what you want.
Method overloading means that you have same method names, but different method signature.
Method signature includes
Method name
Method parameter type
Method parameter sequence
To overload a method, simply create another method of the same method name with a different signature.
Example:
public int getArea(int x)
{
}
public double getArea(double x) //Signature is different, method overloading occurs
{
}
public int getArea(int x, int y) //Signature is different, method overloading occurs
{
}
Note that the return type does not affect the method signature.
It is incorrect if you want to implement method overloading, yet providing different method names.

Incorrect Casting

For some reason I am getting a precision error when I try to compile my code. The precision error comes in the return of my second method where I am trying to calculate the circumference. What am I doing incorrectly?
public class Methods2
{
public static final double PI = 3.14;
public static double calcCirc(double x)
{
return PI*x;
}
public static int calcCirc(int x)
{
return (2*(double) x)*PI;
}
public static void main(String[]args)
{
System.out.println(calcCirc(10.2));
System.out.println(calcCirc(4));
}
}
You are attempting to return a double value in a method declared to return an int. Java won't let you implicitly narrow your value like that.
If you're okay with the loss of precision, then explicitly cast the value to int -- Java will let you do that.
return (int) ((2*(double) x)*PI);
However, I would change the method to return double instead, not to lose precision:
public static double calcCirc(int x)
... as you already did with your other calcCirc method.
Both versions of calcCirc() ought to return doubles.
Also, side note--consider using different method names since they accept inputs that differ not only in type but also in semantics.
E.g. calcCircFromRadius(double radius), calcCircFromDiameter(double diameter). There's not really a reason to take an int as an input type here since Java will automatically cast ints to doubles for you.
try
public static int calcCirc(int x){
return (int)((2*x)*PI);
}

inheritance class fraction/integer

So, I created a simple class named Test, as follows:
import prog.utili.IntegerB;
//It's a custom class
class Test
{
public static void main(String[] args)
{
IntegerB a = new IntegerB(1);
IntegerB b = new IntegerB(2);
IntegerB sum = a.plus(b);
System.out.println(sum);
}
}
I wanted to practise with inheritance so I created two custom classes. Fraction...
package prog.utili;
public class Fraction
{
private int num;
private int den;
public Fraction(int x, int y)
{
[...]
}
public Fraction(int x)
{
this(x, 1);
}
public Fraction plus(Fraction f)
{
int n = this.num * f.den + this.den * f.num;
int d = this.den * f.den;
return new Fraction(n, d);
}
[...]
}
...and IntegerB:
package prog.utili;
public class IntegerB extends Fraction
{
public IntegerB(int num)
{
super(num);
}
public IntegerB plus(IntegerB other)
{
return (IntegerB)this.plus(other);
}
}
The problem is I keep getting the same error:
at prog.utili.IntegerB.plus(IntegerB.java:11)
I know I could simply solve the problem by just deleting the last method on IntegerB and replacing the 9th line of Test.java with
IntegerB sum = (IntegerB)a.plus(b)
but I absolutely want to do it using the inheritance rules over the "plus" method!
To implement the method plus(IntegerB), you call plus(IntegerB), which calls plus(IntegerB), etc. etc. until you get a StackOverflowError.
Provide an actual implementation for your method:
return new IntegerB(this.getNum() + other.getNum());
or
return new IntegerB(super.plus(other).getNum());
Also note that replacing the last line of Test.java by
IntegerB sum = (IntegerB)a.plus(b);
wouldn't work, since the plus() method in Fraction doesn't return an IntegerB, but a Fraction. You would thus get a ClassCastException.
The problem here is that IntegerB.plus does not override Fraction.plus, it overloads it. This is because the argument types are different. Thus when IntegerB.plus calls this.plus(other), it ends up calling itself, which then calls itself, which then calls itself until you get a StackOverflow (thus sending you to stackoverflow : )).
It seems like you want to call plus(Fraction) instead of plus(IntegerB). To do that, you can explicitly upcast other:
return plus((Fraction) other);
This cast has no effect other than to tell the compiler that you want to call the version of plus that handles Fractions, even though you know you have an IntegerB.
However, this method would not return an IntegerB, but just a Fraction whose denominator is 1. You could conceivably override plus to return an IntegerB if the denominator of the result is 1, but that might lead to unexpected situations where a.plus(b) is not equal to b.plus(a) because one is a Fraction while the other is an IntegerB. Alternatively, you could return IntegerB objects from Fraction.plus when possible.

Error in java method?

I have some simple java code to call a method with a value to calculate the volume. I just get error like missing ; in JCreator? What is wrong? This is new beginners non object programming level course. Therefore i guess there should be no public static in the method?
public class Matematik {
public static void main(String[] args) {
System.out.println(volym(10));
double volym(int tal){
return round((4 * math.pi * math.pow(tal,3) / 3),2);
}
}
}
The declaration for volym should not be in main:
public class Matematik {
public static double volym(int tal){
return round((4 * math.pi * math.pow(tal,3) / 3),2);
}
public static void main(String[] args) {
System.out.println(volym(10));
}
}
Edit: it's worth noting that you have other issues too. Namely, java.lang.Math.PI (note the casing) and Math.pow. And Math.round....
You can't define a method inside a method. This would be more obvious if you use the IDEs code formatting. Move one of the } up to before the second method (BTW it must be static as well)
Also its Math not math and Math.round on take one value which it rounds to an integer.
If you want to round to two decimal places you can do
Math.round(x * 100) / 100.0;

Categories