Bit stuck on a bit of my Java code. I have adjusted the code below to give a trivial example, the answers will still be applicable. Basically,
I have three class files: GUI, main, pipe1.
My GUI accepts some values for variables: length and height.
It then calls main.makePipe which is a static method containing an if statement which then creates a new pipe1 called createdPipe. Sample:
public static void makePipe(double length, double width){
if(length > 0 && length < 4){
pipe createdPipe = new pipe1(length, height);
Now my new createpipe object has a method called basicCost which makes returns the cost of the pipe:
protected void calculateCost(){
double basicCost = height * length + 300;
return basicCost;
}
I'm stuck on how to get this returned value all the way back to the GUI class?
If I run (in my GUI class):
createdpipe.calculateCost();
it says cannot find symbol. Rightly so.
If I create a method in main and put:
public double finalCost(){
pipeCost = createdPipe.calculateCost();
return pipeCost;
}
and try to call it from my GUI (main.finalCost) I get an: non static method cannot be reference from a static context.
I understand why, but can anyone tell me how I can make this object known to the GUI class or a way I can calculate data on the pipe1 class and return the data to the GUI class to be used?
the createdPipe is a local variable, so you need to change the scope of this variable.
you should declare a static variable reference to the createdPipe Object in main, like this:
private static pipe1 createdPipe;
change the makePipe method, so it will create createdPipe:
public static void makePipe(double length, double width){
if(length > 0 && length < 4){
createdPipe = new pipe1(length, height);
then you should declare the finalCost as static method:
public static double finalCost()
because createdPipe can be null, you should check if createdPipe is null in finalCost method.
Related
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
public class JustPractice {
public int points=0;
public static void main(String args[]) {
JustPractice ha = new JustPractice();
ha.end();
happy();
}
public void end() {
this.points=100;
System.out.println(points);
}
public static void happy() {
JustPractice object = new JustPractice();
System.out.println(object.points);
return;
}
}
The above is displaying:
100 0
whereas it should be displaying:
100 100
You are looking at two different instances of your class.
Every instance gets their own copy of the instance fields, and they are completely independent from each-other.
JustPractice ha = new JustPractice();
ha.end(); // this one has "100"
JustPractice object = new JustPractice(); // this one has "0"
System.out.println(object.points);
The static method can only access ha's instance fields if you provide it with a ha as a parameter.
Make points static. Then you got what you want.
public static int points=0;
make points static will keep only one variable for all instance of your class.
Else each initialization will create separate individual variable and will assign the value to 0
its because of when method is making new object then that time it will having another copy as of the reference object will be having independent copy per object of the class remember the java basic?
and if u will make int as static object then it will give your output what u want and what u asking for simple example from yours is
public static int points = 0;
public void end() {
this.points = 100;
System.out.println(points);
}
public static void happy() {
CheckingClass object = new CheckingClass();
System.out.println(object.points);
return;
}
public static void main(String args[]) {
CheckingClass ha = new CheckingClass();
ha.end();
happy();
}
hope it helpful
it is displaying as 100 0 instead of 100 100 because you are creating a new instance of class JustPractice in your happy() method, instead of passing reference i.e. ha of existing instance.
new newly created instance is showing the default value that that u have given in your class, i.e. 0.
You set value of the points instance variable in end method.and for the object in happy method you don't initialize the points instance variable of object.
So it gets the default value 0.
A static method can access a non-static object, but only if it is passed to the method. Given that the static method in question is the method in which the program begins, you have no ability to pass anything to it.
What it cannot do, within the scope of a non-static class, is access any of the instance members or functions. The problem is not that you're instantiating ha from a static method, it's that you're accessing the member points, which is an instance member that belongs to every instantiation of your class.
In order to fix this, you can either pass points to the instance of JustPractice (ha) that you're creating, and have one of JustPractice's methods return the final value, or you can make points, end() and happy() static as well, in which case all can work happily with one another.
I am writing a program to mimic the "Deal or No Deal" game.
Background on Deal or No Deal: http://en.wikipedia.org/wiki/Deal_or_No_Deal
In working up to the final product, I have written various classes. However, I am trying to test one of my classes, and continue to get the NullPointerException.
I wrote a class called Box, that creates "box" objects. The box object is the actual box that a player picks. It consists of a true/false value and a double boxValue. The boolean variable denotes whether it's open/closed (true for open, false for closed). The double boxValue is the actual value assigned to the box.
public class Box {
//instance fields
private double boxValue; // the amount of $ in each box
private boolean openClose; // whether or not the box is closed
//Constructor
public Box(double boxValue) {
this.openClose = false;
this.boxValue = boxValue;
if (boxValue < 0) {
throw new IllegalArgumentException("Box value must be greater than 0");
}
}
}
I have written another class called BoxList as well. This creates a Box object array that will serve as the playing board, when combined with further classes that I am planning to write. The main idea is that the constructor in BoxList creates the array by using a passed in double array as a paramater, and then creates a Box Object array of the same length of the passed in double array, and assigns the double value of each element of the parameter array, to the value of the Box object array as the corresponding element.
I wrote a sample main method to test, but when I try to get the value of a particular element of a Box in the BoxList array, I get the NullPointerException. Can anyone offer advice to help trouble shoot this.
(These are snips of a larger program...I already wrote so much that I didn't want to clog further)
public class BoxList {
private Box[] boxArray;
public BoxList(double[] monetaryAmounts) {
Box[] boxArray = new Box[monetaryAmounts.length];
for (int i = 0; i < boxArray.length; i++) {
boxArray[i] = new Box(monetaryAmounts[i]);
}
}
public double getValue(int index) {
return boxArray[index].getValue();
}
// A sample main method to test out various object methods
public static void main(String[] args) {
double[] monetaryAmounts = {.5, 1, 3, 7.5, 8, 10}; // test array
BoxList test = new BoxList(monetaryAmounts);
System.out.println(test.getValue(0));
}
You initialized your boxArray properly, but you initialized a local variable boxArray, and your instance variable boxArray was unreferenced, so Java initialized it to null, causing the exception. Change
Box[] boxArray = new Box[monetaryAmounts.length];
to
boxArray = new Box[monetaryAmounts.length];
I am trying to pass a value from the main method and set it to a private variable. Here is the main method that's pertinent:
import java.util.*;
public class Experiment{
private static Extension extension=new Extension();
public static void main(String[] ars);{
Scanner input=new Scanner(System.in);
System.out.print("Enter the length: ");
int length=input.nextInt;
extension.messages(length); }
}
and here's what goes with it:
public class Extension{
private int theLength;
public void Extension(int length){
theLength=length; }
public void setLength(int length){
theLength=length; }
public int getLength() {
return theLength }
public void messages(int length){
System.out.println("theLength: "+theLength);
System.out.println("Length: "+getLength(); }
}
I added the extra display because I wanted to see if the value was getting passed on correctly. When I run it, I realize that it's not; both theLength and length are set to zero despite having input different numbers. Can anyone see what I'm doing wrong? I would sincerely appreciate a thorough answer (since I am just starting out).
You are not setting the private variable length. You should call the setLength(int length) method.
change to this
System.out.print("Enter the length: ");
int length=input.nextInt;
extension.setLength(length); // this will set the private variable
extension.messages(length);
This is a lesson in encapsulation. Your issue, as #salihrkc said, is that you're never actually setting the length variable which exists in your "Extension" object. If you try to print "length" as passed in to your object, you'll see it's getting there just fine.
You act on your object using the dot operator (e.g. extension.messages(length);, to call the messages method). The key points you should be realizing is that you cannot set the objects length by just doing extension.theLength = length;. This is because of the private modifier. Instead you should be using the "getter" and "setter" methods. These functions exist within your object and therefore access to the private variables, so you can do something like extension.setLength(length); and System.out.println(extension.getLength());
Check out the two sources I linked, they'll help.
Good luck.
I had an an assignment with this question
Write a function maxArray which receives an array of double's and returns the maximum value in the array. using this function
double maxArray(double dar[], int size);
I did what he want and I had problem with the calling sentence within the main method !!
here is my code :
public class Q3 {
public static void main(String[] args) {
double dar[] = { 22.5 , 10.23 , 15.04 , 20.77 };
double max = maxArray(dar,4);
System.out.println("the largest number is : " + max);
}
double maxArray(double dar[], int size) {
double maxV = 0;
for (int i = 0; i < dar.length; i++) {
if (dar[i] > maxV ) {
maxV = dar[i];
}
}
return maxV;
}
}
The reason you can't call your method from main() is that main() is static whereas your method isn't.
Change it to:
static double maxArray(double dar[], int size)
While you're at it, remove size since it's not necessary.
It is probably also worth noting that your method would fail if the array were to contain negative numbers.
your maxArray method is a non static method. you cannot access non-static methods from static methods without an instance of the class, you should create an instance of your class and call maxArray method
double max = new Q3().maxArray(dar,4);
Or alternatively, you could always mark your maxArray method static and call it directly from main method.
Declare your maxArray as static, so you can access it as from a static method main()
or
You create an instance of your class and call it from the object.
your issue is you are trying to call maxArray, a non-static method, from your main method, which is static. That's a problem because a non-static method can only be called from an instance of the class, whereas a static method is called via the class itself.
Either make your maxArray a static method, or initialize a Q3 object in your main method, and call maxArray like that.
Your method has to be static, so you have to say
static double maxArray(double dar[], int size)
Here are some hints how you could improve your method:
since you don't use the value "size" once, you can either throw it out or replace the i < dar.length with i < size.
Also, when initializing maxV in the maxArray method, you might want to use the first value of the array (double maxV = dar[0]), because if all doubles in the array are negative, maxV with the number 0 will be the highest. (You could also use the lowest double value possible by saying double maxV = Double.MIN_NORMAL).
1) make your method static
2) Remember in java use BigDecimal class to do any decimal arithmetic.