how to call an instance method in another class - methods

public class circle
{
double circle1;
double Xvalue;
double Yvalue;
double radius;
public double area = (3.14*(this.radius * this.radius));
public double getArea ()
{
return area;
}
}
//this is my second class that will create the objects
public class tester
{
public static void main(String args [])
{
circle circle1 = new circle();
circle1.Xvalue = 1;
circle1.Yvalue = 2;
circle1.radius = 4;
System.out.println(getArea());
//im not too sure why the print statement won't print the method getArea.
}
}

You need System.out.println(circle1.getArea());, otherwise it's trying to find a method called getArea() in your Tester class which has no such method.
Also, your code will always return an area of 0. This is because of how you initialize your data:
When you create your new circle object it creates xValue and because it is a primitive type (double instead of Double) it defaults to giving it a value of 0 (because it must have some value).
So when it gets down to where you define the area variable at that moment (since it is still creating your object, it does (area = 3.14*(0.0 * 0.0)) which is going to be 0.
What you really want is something more like this:
public class Circle {
double Xvalue;
double Yvalue;
double radius;
public Circle(double xValue, double yValue, double radius) {
this.xValue = xValue;
this.yValue = yValue;
this.radius = radius;
}
public double getArea ()
{
return 3.1415926*(this.radius * this.radius);
}
}
public class Tester
{
public static void main(String[] args)
{
Circle circle1 = new Circle(1, 2, 4);
System.out.println(circle1.getArea());
//im not too sure why the print statement won't print the method getArea.
}
}

Related

Error messages that don't make sense regarding syntax when there is already a bracket or ;

This is the code I made to attempt to calculate the perimeter and area of a rectangle.
public class Rectangle
{
public static void main (String [ ] args)
private double side1;
private double side2;
new Rectangle( )
{
This is where I get the first error
side1 = 1;
side2 = 1;
}
public Rectangle (double s1, double s2)
{
side1 = s1;
side2 = s2;
}
public double computePerimeter()
{
double perimeter;
perimeter = (side1 * 2) + (side2 *2);
return perimeter;
}
public double computeArea()
{
double area;
area = side1 * side2;
return area;
}
public double getSide1()
{
return side1;
}
public double getSide2()
{
return side2;
}
public void setSides(int firstSide, int secondSide)
{
side1 = firstSide;
side2 = secondSide;
}
public String toString()
{
System.out.println("Area is " + area);
System.out.println("Perimeter is " + perimeter);
}
{
Scanner scan = new Scanner(System.in);
int sideOne = scan.nextInt();
side1 = sideOne;
int sideTwo = scan.nextInt();
side2 = sideTwo;
computePerimeter();
computeArea();
}
This is where I keep getting the other two errors
}
}
I keep getting this message, but after line 10 I have a { and after line 67 a }. I'm just pretty confused.
"3 errors found:File: C:\Users\jrader\Desktop\GridWorldCode\projects\firstProject\Rectangle.java [line: 10] Error: Syntax error on token "{", { expected after this token [line: 67] Error: Syntax error, insert "}" to complete ClassBody [line: 67] Error: Syntax error, insert ";" to complete Statement"
This is a class definition so there is no main method, only constructors and method declarations. I realized my mistake.

How can I display pixel by pixel the calculation of a circle?

Few days before, I asked you to help me because I couldn't show the drawing of a circle pixel by pixel (the drawing got stuck). #James_D found the solution and told me it was because a background-thread was trying to modify the UI. Indeed, I have a GraphicEngine class that extends Service : this class is this background-thread and its aim was to calculate and modify the image (now its aim is just to calculate the circle's pixels).
Well, finally, thanks to #James_D, I have now some classes :
GraphicEngine,
ImageAnimation which contains the animation of drawing,
DialogCreationOfCircularGradation, which is a dialog containing a button "OK, draw circle !" and which handles this event.
The below source contains the answer of my program to the user-event "Draw a circle". It gets several Textfield's input and give it to the GraphicsEngine. Moreover it asks the latter to do the calculation of the circle's pixels and asks the ImageAnimation to display the calculation pixel by pixel, during the calculation done by the GraphicsEngine.
CLASS DialogCreationOfCircularGradation
public void dialogHandleEvents() {
Optional r = this.showAndWait();
if(r.isPresent() && r.get() == ButtonType.OK) { // The user clicks on "OK, draw the circle !"
int radius = Integer.parseInt(this.dialog_field_radius.getText());
[...]
this.gui.getImageLoader().loadImageFromUsersPreferences(x0 + thickness + 2*radius, y0 + thickness + 2*radius);
this.gui.getGraphicEngine().setOperationToDo("Circle");
this.gui.getGraphicEngine().setRadius(radius);
[...]
this.gui.getGraphicEngine().restart();
this.gui.getImageAnimation().start();
}
}
The below code is GraphicsEngine's one. As you can see, there is in particular one important variable which is incremented during the circle algorithm : its name is counter_max. Why this variable is important ? Because it's necessary used in the class ImageAnimation. Look at its source after GraphicsEngine's one.
CLASS GraphicEngine
public class GraphicEngine extends Service<Void> {
private int image_width, image_height;
private PixelReader pixel_reader;
private BlockingQueue<Pixel> updates;
private String operation_to_do;
private int radius; [...]
public void setOperationToDo(String operation_to_do) {
this.operation_to_do = operation_to_do;
}
public Task<Void> createTask() {
return new Task<Void>() {
protected Void call() {
switch(operation_to_do) {
[...]
case "Circle" :
traceCircularGradation();
break;
}
return null;
}
};
}
private void traceCircularGradation() {
double w = 2 * 3.141, precision = 0.001;
long counter_max = 0;
int x, y;
this.gui.getImageAnimation().setMax(counter_max);
double[] rgb_gradation;
for (double current_thickness = 0; current_thickness <= this.thickness; current_thickness++) {
for (double angle = 0; angle <= w; angle += precision) {
x = (int) ((current_thickness + radius) * Math.cos(angle) + x0);
y = (int) ((current_thickness + radius) * Math.sin(angle) + y0);
if(x >= 0 && y >= 0) {
counter_max++;
rgb_gradation = PhotoRetouchingFormulas.chromatic_gradation(angle, w);
updates.add(new Pixel(x, y, Color.color(rgb_gradation[0], rgb_gradation[1], rgb_gradation[2])));
}
}
}
this.gui.getImageAnimation().setMax(counter_max);
}
The variable counter_max is used in ImageAnimation (its name has changed, its called : max). It's useful in the last if : if (count >= max).
max/counter_max represent the number of modified pixels. I can't replace it with image_width * image_height because in the circle algorithm, only the circle's pixels are drawn/modified. The other pixels of the image are not.
So I have either to compute counter_max as I did here in the for loops and then give it to ImageAnimation, or find a mathematical formula to determine it before the for. In the first case, the display of the circle doesn't work.
It would be really perfect if a formula existed.
CLASS ImageAnimation
public class ImageAnimation extends AnimationTimer {
private Gui gui;
private long max;
private long count, start;
ImageAnimation (Gui gui) {
this.gui = gui;
this.count = 0;
this.start = -1;
}
public void setMax(long max) {
this.max = max;
}
#Override
public void handle(long timestamp) {
if (start < 0) {
start = timestamp ;
return ;
}
WritableImage writable_image = this.gui.getWritableImage();
BlockingQueue<Pixel> updates = this.gui.getUpdates();
while (timestamp - start > (count* 5_000_000) / (writable_image.getWidth()) && ! updates.isEmpty()) {
Pixel update = updates.remove();
count++;
writable_image.getPixelWriter().setColor(update.getX(), update.getY(), update.getColor());
}
if (count >= max) {
this.count = 0;
this.start = -1;
stop();
}
}
public void startAnimation() {
this.start();
}
}
If you need to compute max later, then you can't initialize it to zero (because if you do any updates before it is set to its "correct" value, then count will exceed max and you will stop the animation). So just initialize it to something it will never reach, e.g. Long.MAX_VALUE.
Relatedly, since you are accessing max from multiple threads, you should either synchronize access to it, or (better) use an AtomicLong. I.e.
public class ImageAnimation extends AnimationTimer {
private Gui gui;
private AtomicLong max;
private long count, start;
ImageAnimation (Gui gui) {
this.gui = gui;
this.count = 0;
this.start = -1;
this.max = new AtomicLong(Long.MAX_VALUE);
}
public void setMax(long max) {
this.max.set(max);
}
#Override
public void handle(long timestamp) {
if (start < 0) {
start = timestamp ;
return ;
}
WritableImage writable_image = this.gui.getWritableImage();
BlockingQueue<Pixel> updates = this.gui.getUpdates();
while (timestamp - start > (count* 5_000_000) / (writable_image.getWidth()) && ! updates.isEmpty()) {
Pixel update = updates.remove();
count++;
writable_image.getPixelWriter().setColor(update.getX(), update.getY(), update.getColor());
}
if (count >= max.get()) {
this.count = 0;
this.start = -1;
this.max.set(Long.MAX_VALUE);
stop();
}
}
public void startAnimation() {
this.start();
}
}

Method error. Method cannot be applied to given types. Required: Double, Found: No arguments

I have an assigment that requires me to read data off a .txt containing gravity levels and then calculate your weight on each planet using methods. There seems to be an issue in the first method with type values? I canno tell. Any advice would be much appreciated.
/**
* Description for 7.04 Weight project
*
`* #author (Your Name)
* #version (The Date)
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
public class Weight
{
// write static methods here
// Note: formula for finding weight on a planet: Earth weight divided by Gravity constant times surface gravity
public static void getGravity(double [] gravity)throws IOException
{
File fileName = new File("gravity.txt");
Scanner inFile = new Scanner(fileName);
int i = 0;
while(inFile.hasNext())
{
gravity[i] = inFile.nextDouble();
}
}
public static void printResults(String[] name, double gravity[] ,double[] weight)
{
for (int i = 0; i <=8; i++)
{
System.out.printf(" %-7s %3.1f %7s", name[i], gravity[i] , weight[i]);
}
}
public static double[] calcWeight(double [] gravity)
{
double myWeight = 100.0;
int i = 0;
for (i = 0; i <= 8; i++)
{
gravity[i] = gravity[i] * myWeight;
}
return gravity;
}
public static void main(String[] args)throws IOException
{
// Extension idea... instead of hard codeing the weight, you may propt the user for input.
double earthWeight = 100.0; // initalize Earth weight to 100 lbs.
String[] names = {"Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune", "Pluto"};
double[] gravity = getGravity(); // static method you write
double[] weight = calcWeight(earthWeight, gravity); // static method you write
printResults(names, gravity, weight); // static method you write
} //end main
}//end class
Here's your problem:
calcWeight(earthWeight, gravity); //passes two parameters
public static double[] calcWeight(double [] gravity) //takes one paramter
The method call does not match the method definition.

Stop Skeleton Flickering in Kinect for Windows

Currently working on a project to find the X,Y position of the using who is standing in front of the kinect.
Even though the user is standing still the X,Y keep changing because the kinect skeleton is flickering. Could someone help me how to figure out a way to stop the skeleton flickering
Have you set the smoothing parameter? The following settings result in very smooth movements, but with a lot of latency.
TransformSmoothParameters smoothingParam = new TransformSmoothParameters
{
Smoothing = 0.7f;
Correction = 0.3f;
Prediction = 1.0f;
JitterRadius = 1.0f;
MaxDeviationRadius = 1.0f;
};
sensor.SkeletonStream.Enable(smoothingParam);
If that is not working good enough for you, I had developed a helper class for one of my kinect projects to smooth the coordinates of joints. You have to create an instance of the following helper class for each smoothed joint and call GetSmoothedXPosition/GetSmoothedYPosition with the screen coordinates of the joint:
internal class JointSmoothing
{
#region Constants and Enumerations
private const int QueueLength = 7;
private const double BaseValue = 0.9;
#endregion
#region Fields
private readonly Queue<double> myXValues = new Queue<double>(QueueLength);
private readonly Queue<double> myYValues = new Queue<double>(QueueLength);
#endregion
#region Public Methods
public double GetSmoothedXPosition(double x)
{
if (myXValues.Count >= QueueLength)
{
myXValues.Dequeue();
}
myXValues.Enqueue(x);
return ExponentialMovingAverage(myXValues);
}
public double GetSmoothedYPosition(double y)
{
if (myYValues.Count >= QueueLength)
{
myYValues.Dequeue();
}
myYValues.Enqueue(y);
return ExponentialMovingAverage(myYValues);
}
public void Clear()
{
myXValues.Clear();
myYValues.Clear();
}
#endregion
#region Private Implementation
private static double ExponentialMovingAverage(Queue<double> values)
{
double numerator = 0;
double denominator = 0;
int valueCount = values.Count;
int weight = valueCount - 1;
foreach (double value in values)
{
numerator += value * Math.Pow(BaseValue, weight);
denominator += Math.Pow(BaseValue, weight);
weight--;
}
double average = values.Sum();
average /= values.Count;
numerator += average * Math.Pow(BaseValue, valueCount);
denominator += Math.Pow(BaseValue, valueCount);
return numerator / denominator;
}
#endregion
}

GWT - Fading in/out a background image

I have a custom class as follows which works fine, the button grows/shrinks to accomodate the text and the bg image changes on a click.
Probem I want to solve is how to "fadeIN" one or other image when clicked/notClicked is called
Here is my code
public ExpandingOvalButton(String text) {
if (text.length() > 15) {
label.getElement().getStyle().setFontSize(20, Unit.PX);
} else {
label.getElement().getStyle().setFontSize(30, Unit.PX);
}
int width = 120;
initWidget(panel);
label.setText(text);
// width = width + (text.length() * 8);
String widthStr = width + "px";
image.setWidth(widthStr);
image.setHeight("100px");
button = new PushButton(image);
button.setWidth(widthStr);
button.setHeight("50px");
panel.add(button, 0, 0);
panel.add(label, 18, 14);
}
public void isClicked()
{
image.setUrl("images/rectangle_green.png");
}
public void unClicked()
{
image.setUrl("images/rectangle_blue.png");
}
#Override
public HandlerRegistration addClickHandler(ClickHandler handler) {
return addDomHandler(handler, ClickEvent.getType());
}
public void setButtonEnabled(boolean enabled) {
// panel.setVisible(enabled);
// this.label.setVisible(enabled);
this.button.setVisible(enabled);
}
Here's a general utility class to fade any element:
public class ElementFader {
private int stepCount;
public ElementFader() {
this.stepCount = 0;
}
private void incrementStep() {
stepCount++;
}
private int getStepCount() {
return stepCount;
}
public void fade(final Element element, final float startOpacity, final float endOpacity, int totalTimeMillis) {
final int numberOfSteps = 30;
int stepLengthMillis = totalTimeMillis / numberOfSteps;
stepCount = 0;
final float deltaOpacity = (float) (endOpacity - startOpacity) / numberOfSteps;
Timer timer = new Timer() {
#Override
public void run() {
float opacity = startOpacity + (getStepCount() * deltaOpacity);
DOM.setStyleAttribute(element, "opacity", Float.toString(opacity));
incrementStep();
if (getStepCount() == numberOfSteps) {
DOM.setStyleAttribute(element, "opacity", Float.toString(endOpacity));
this.cancel();
}
}
};
timer.scheduleRepeating(stepLengthMillis);
}
}
Calling code for instance:
new ElementFader().fade(image.getElement(), 0, 1, 1000); // one-second fade-in
new ElementFader().fade(image.getElement(), 1, 0, 1000); // one-second fade-out
You could use GwtQuery. It provides fadeIn & fadeOut effects (and many other JQuery goodies), it is cross-browser compatible and seems to be pretty active.

Resources