non-static method from static context - java

Why I cannot reffer? Do You know how to fix it? I would like to draw line by DDA algorithm.
Please help.
import java.awt.*;
import java.awt.event.*;
import java.lang.String.*;
import java.util.Scanner;
import java.io.IOException;
import javax.swing.*;
class Test extends JPanel {
private void JPanel1MouseClicked(MouseEvent evt){
int x = evt.getX();
int y = evt.getY();
System.out.println("X to: " + x + " Y to: " + y);
}
public void sprawdz(double xx1, double xx2, double yy1, double yy2){
}
public static void main(String[] args) {
String x1;
String x2;
String y1;
String y2;
Scanner sc = new Scanner(System.in);
System.out.print("Podaj pierwsza wspolrzedna pierwszego punktu: ");
x1 = sc.nextLine();
System.out.print("Podaj druga wspolrzedna pierwszego punktu: ");
x2 = sc.nextLine();
System.out.print("Podaj pierwsza wspolrzedna drugiego punktu: ");
y1 = sc.nextLine();
System.out.print("Podaj druga wspolrzedna drugiego punktu: ");
y2 = sc.nextLine();
//DDA2 nowy = new DDA2(x1, x2, y1, y2);
Test nowy = new Test();
DDA2.licz(x1, x2, y1, y2);
JFrame ramka = new JFrame();
ramka.setSize(300,300);
ramka.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ramka.getContentPane().add(new Test());
ramka.setVisible(true);
// JPanel jp = new JPanel();
// jp.setBackground(Color.WHITE);
// jp.setSize(100,100);
// jp.setLayout(new BorderLayout());
// jp.setVisible(true);
}
class DDA2 {
double dxx1 = Double.parseDouble(xx1);
double dxx2 = Double.parseDouble(xx2);
double dyy1 = Double.parseDouble(yy1);
double dyy2 = Double.parseDouble(yy2);
double dx = x2 - x1;
double dy = y2 - y1;
public void licz(String xx1, String xx2, String yy1, String yy2){
if (Math.abs(dx) >= Math.abs(dy))
{
double m = Math.abs(dx);
System.out.println("DX" + m);
}
else
{
// ALGORYTYM PRZYROSTOWY
double m = Math.abs(dy);
//System.out.println("DY" + m);
double x = dxx1;
double y = dyy1;
for (int i=1; i <= m; i++)
{
x = x + dx/m;
y = y + dy/m;
}
}
System.out.println("Wspolrzednie punktu pierwszego to: " + "(" + dxx1 + "; " + dxx2 +")");
System.out.println("Wspolrzednie punktu drugiego to: " + "(" + dyy1 + "; " + dyy2 + ")");
}
}
// public void paintComponent(Graphics g){
// super.paintComponent(g);
// g.setColor(Color.RED);
// g.fillRect((int) x, (int) y, 1, 1);
// }
}

Make the licz method static. You are calling it without an instance. Furthermore - you have instance variables that depend on method parameters - this is not directly possible. Move them in the method body as well.
Generally speaking, you have two options:
have everything static - if you don't require your an object that has some state, and each invocation is a one-time operation on some given parameters, then this is the proper way to go. I think this is your case.
have an instance. Construct it with a given set of parameters that you want to reuse throughout invocations. Then declare the methods non-static and decide which variables should belong to the instance.

The method DDA2.licz() is not declared static since it uses fields of class DDA2 which are not static also. Thus it can only be applied to an instance of DDA2 but not in a static context (i.e. something like DDA2 d = new DDA2(); d.licz(...); will work but not DDA2.licz(...);).

You need to instantiate DDA2 and call licz on the new instance of that class. You nearly have the correct code commented out.
Replace DDA2.licz(x1, x2, y1, y2) with
DDA2 nowy = new DDA2();
nowy.licz(x1, x2, y1, y2);
Edit: Missed the broken definition of DDA2 altogether. #Bozho's answer is the correct one.

In this case, the DAA2 is an inner class.
So you can't made it's methods static.
You should make DDA2 class static and then made the licz method static.
or
Move DAA2 class out of Test class and the use this way :
DAA2 daa2 = new DAA2();
daa2.licz(x1, x2, y1, y2);

Related

calling mutator from within a method of another class

Im trying understand what am I doing wrong here
import java.lang.Math
public class QuadraticEquation {
public static Roots findRoots(double a, double b, double c) {
double d = b*b-4*a*c;
double x1 = (-b + Math.sqrt(d))/2*a;
double x2 = (-b - Math.sqrt(d))/2*a;
Roots( x1, x2);
}
public static void main(String[] args) {
Roots roots = QuadraticEquation.findRoots(2, 10, 8);
System.out.println("Roots: " + roots.x1 + ", " + roots.x2);
}
}
class Roots {
public final double x1, x2;
public Roots(double x1, double x2) {
this.x1 = x1;
this.x2 = x2;
}
}
Obviously it gives me a error: cannot find symbol on last line of public static Roots findRoots but I don't understand what other way of calling the mutator is there
What's wrong with replacing
Roots(x1, x2);
with
return new Roots(x1, x2);
?
Also, I don't know what your understanding of a "mutator" is, but the keyword you might want to look up in your Java beginners guide is "constructor".

Method from other class and use of toString()

I am trying to make this code work, receive 2 points (x, y) & (x1,y1) from user on MAIN and use a method from another class and get the calculation.
Also it would be very nice to receive an explanation about toString.
import java.util.Scanner;
public class Test{
public static void main(String[]args)
{
Scanner scan = new Scanner(System.in);
double x , y , x1 , y1;
Pytaguras Triangle = new Pytaguras();
System.out.println("Hello , this program is using Pytagoras formula" +
" on the 4 point that you enter");
System.out.println("Please enter 4 points to calculate the distance");
x = scan.nextDouble();
y = scan.nextDouble();
x1 = scan.nextDouble();
y1 = scan.nextDouble();
Triangle.setDouble( x, y, x1, y1);
System.out.println("the distance between 2 points is :" + Triangle.calculate() );
}
}
public class Pytaguras
{
private double x, y, x1 ,y1 ;
public void setDouble(double _x, double _y, double _x1, double _y1)
{ _x=x;
_y=y;
_x1=x1;
_y1=y1;}
public double calculate(double _x , double _y , double _x1 , double _y1 )
{ double s;
s = Math.sqrt((_x-_y)*(_x-_y)+(_x1-_y1)*(_x1-_y1));
return s;
}
}
If you would like to receive the distance-calculation via method toString() of your class Triangle, you just need to implement it same like method calculate:
Possible solution using toString
Your class would look like this:
public class Pytaguras {
private double x, y, x1 ,y1 ;
public void setDouble(double _x, double _y, double _x1, double _y1) {
_x=x;
_y=y;
_x1=x1;
_y1=y1;
}
public static double calculate(double _x , double _y , double _x1 , double _y1 ) {
return Math.sqrt((_x-_y)*(_x-_y)+(_x1-_y1)*(_x1-_y1));
}
public String toString() {
return "Distance is " + Math.sqrt((x - y)*(x -y)+(x1 - y1)*(x1 - y1));
}
}
What probably went wrong?
When you tried to implement toString() like this:
// code omitted for clarity
public double calculate(double _x , double _y , double _x1 , double _y1 ) {
double s; // variable declared locally, thus can be used only inside this method
s = Math.sqrt((_x-_y)*(_x-_y)+(_x1-_y1)*(_x1-_y1));
return s;
}
// code omitted for clarity
public String toString() {
return s; // will give compiler-error, since symbol/variable "s" is not visible here, but only inside method calculate
}
// code omitted for clarity
Refactoring = optimizing your code
use static on utility-method : Your calculation method does not depend on any variables (x,y,x1,y1) declared inside the class, but on parameters only. So it is independent and can be made static. Thus would make it a utility-method that can be called from outside like Pytaguras.calculate(...). See Java Tutorial on static.
use constructor for initialization of variables: Your 2 points can be directly initialized by using a constructor. Thus you do not need to call both new Pytaguras() and setDouble(x1, y1, x2, y2). You could simply call new Pytaguras(x1, y1, x2, y2). See Java Tutorial on constructor.
You can simply assign the values through the class constructor.
public class Triangle {
private double x, y, x1 , y1;
public Triangle(double new_x, double new_y, double new_x1, double new_y1) {
x = new_x;
y = new_y;
x1 = new_x1;
y1 = new_y1;
}
public double calculate() {
return Math.sqrt((x-y)*(x-y)+(x1-y1)*(x1-y1));
}
}
And then on your main:
public static void main(String[]args) {
Scanner scan = new Scanner(System.in);
double x , y , x1 , y1;
Pytaguras Triangle = new Pytaguras();
System.out.println("Hello , this program is using Pytagoras formula" +
" on the 4 point that you enter");
System.out.println("Please enter 4 points to calculate the distance");
x = scan.nextDouble();
y = scan.nextDouble();
x1 = scan.nextDouble();
y1 = scan.nextDouble();
Triangle triangle = new Triangle(x, y, x1, y1);
System.out.println("the distance between 2 points is :" + triangle.calculate());
}

Number Line using Java Graphics API

I am trying to create a number line with labelled x-axis.Two problems:
Everything works fine for 0-9. But anything after that, the numbers get squashed together and not properly oriented on the scale.
My main axis line tends to disappear every time I try maximizing my window or at times it just wouldn't appear at all.Every time any of these happen, I have to re-compile my code and it works just fine.
Any help with the above problems will be greatly appreciated.
import java.awt.Graphics;
import javax.swing.JFrame;
/**
* #author Emil Shirima
*
*/
public class Drawing extends JFrame {
/**
* #param args
*/
int width = 300, height = 300, spacing = 10;
int x1 = 0, y1 = 150, x2 = 300, y2 = 150;
public Drawing() {
setTitle("Trial");
setSize(width, height);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
#Override
public void paint(Graphics brush) {
brush.drawLine(x1, y1, x2, y2);
x1 = 10;
y1 = 150;
x2 = 10;
y2 = 130;
// brush.drawLine(x1, y1, x2, y2);
for (int i = 0; i < 12; ++i) {
String ID = Integer.toString(i);
x1 = x2 += spacing;
brush.drawLine(x1, y1, x2, y2);
if (i < 10) {
brush.drawString(ID, x1 - 3, y2 + 40);
} else {
// With the below implementation, the numbers overlap each other
// and are not properly oriented on the axis
brush.drawString(ID, x1 - 3, y2 + 40);
// TODO: I need to resize the numbers after 10 so as they fit
// properly on the scale
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Drawing draw_object = new Drawing();
}
Current implementation:
Maximized GUI:
Your main problem:
You change x1, x2 within your paint method, and these changes will persist on the next painting. In other words, you're changing the state of the object within a rendering method, something that you must avoid doing.
You're using "magic" numbers making your program difficult to debug.
Other associated problems:
You're drawing directly in a JFrame, something that the Swing painting tutorials tell you exactly not to do since there are risks of significant side effects.
Instead draw in a JPanel's paintComponent method method.
You're not calling any super painting method, thus breaking the painting chain.
If you want the number line to extend through the component, get the component's size in the painting method (again, paintComponent) and use that to help determine the placement of the line.
Also consider sprinkling in a little FontMetrics to help place your numeric text. For example the following code creates a realizable number line:
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import javax.swing.*;
#SuppressWarnings("serial")
public class SimpleNumberLinePanel extends JPanel {
private static final int PREF_W = 800;
private static final int PREF_H = 300;
private static final int GAP = 10;
private static final int START = 0;
private static final int END = 12;
private static final int VERT_LINE_HEIGHT = 20;
private static final Font FONT = new Font(Font.MONOSPACED, Font.BOLD, 14);
private static final int TEXT_GAP = 2;
#Override
protected void paintComponent(Graphics g) {
// call super method
super.paintComponent(g);
int width = getWidth();
int height = getHeight();
// initialize these guys each time paintComponent is called
int x1 = GAP;
int y1 = height / 2;
int x2 = width - 2 * GAP;
int y2 = y1;
g.drawLine(x1, y1, x2, y2);
for (int i = START; i <= END; i++) {
int x = (i * (x2 - x1)) / (END - START) + GAP;
drawNumberAndLine(g, i, x, y1, VERT_LINE_HEIGHT);
}
}
private void drawNumberAndLine(Graphics g, int number, int x, int y,
int vertLineHeight) {
int x1 = x;
int y1 = y;
int x2 = x;
int y2 = y - vertLineHeight;
g.drawLine(x1, y1, x2, y2);
String text = String.valueOf(number);
g.setFont(FONT);
FontMetrics fontMetrics = g.getFontMetrics();
int textX = x - fontMetrics.stringWidth(text) / 2;
int textY = y + fontMetrics.getHeight() + TEXT_GAP;
g.drawString(text, textX, textY);
}
#Override // make GUI bigger
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
private static void createAndShowGui() {
JFrame frame = new JFrame("Number Line");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new SimpleNumberLinePanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}

Finding length and angles of a triangle

My job is to compute the following properties of a given triangle: lengths of all sides, angles at all corners, the perimeter and the area. I have a Triangle class and a Triangle tester class. I THINK I have coded the perimeter and area correctly? But I am beginning to think instead of setting a constant variable side for my perimeter I should be using the lengths of all sides to find my perimeter as well. What I am stuck on is finding the lengths and the angles. For some reason when I run my tester class they all come out as 1.0. Any advice would be appreciated! Thank you!
import java.util.Scanner;
public class Triangle
{
Scanner in = new Scanner(System.in);
/**
* Variables
*/
double x1;
double x2;
double x3;
double y1;
double y2;
double y3;
double lengthA;
double lengthB;
double lengthC;
double angleA;
double angleB;
double angleC;
double area;
double perimeter;
double base;
double height;
double p;
/**
Constructs x and y coordinates
#param x1, x2, x3 to x1, x2, x3
#param y1, y2, y3 to y1, y2, y3
*/
public Triangle(double x1, double x2, double x3, double y1, double y2, double y3)
{
this.x1 = x1;
this.x2 = x2;
this.x3 = x3;
this.y1 = y1;
this.y2 = y2;
this.y3 = y3;
}
/**
*Find lengths of all sides
*/
public double getLengthA()
{
lengthA = Math.sqrt(Math.pow((x2 - x1), 2) + Math.pow((y2 - y1), 2));
return lengthA;
}
public double getLengthB()
{
lengthB = Math.sqrt(Math.pow((x3 - x2), 2) + Math.pow((y3 - y2), 2));
return lengthB;
}
public double getLengthC()
{
lengthC = Math.sqrt(Math.pow((x1 - x3), 2) + Math.pow((y1 - y3), 2));
return lengthC;
}
/**
* Find angles at all corners
#return angles at all corners
*/
public double getAngleA()
{
angleA = lengthA + lengthB + lengthC - (lengthB * lengthC);
return angleA;
}
public double getAngleB()
{
angleB = lengthB + lengthA + lengthC - (lengthA * lengthC);
return angleB;
}
public double getAngleC()
{
angleC = lengthC + lengthA + lengthB - (lengthA * lengthB);
return angleC;
}
/**
* Constant Variables
*/
public Triangle()
{
base = 5;
height = 15;
}
/**
* Find perimeter of triangle
*/
public double getPerimeter()
{
perimeter = lengthA + lengthB + lengthC;
return perimeter;
}
public double getHalfPerimeter()
{
p = perimeter / 2;
return p;
}
/**
* Find area of triangle
*/
public double getArea()
{
double area = Math.sqrt(p * (p - lengthA) * (p - lengthB) * (p - lengthC));
return area;
}
}
Here is my tester class:
import java.util.Scanner;
import javax.swing.JOptionPane;
public class TriangleSimulator
{
public static void main (String[] args)
{
Scanner in = new Scanner(System.in);
String input = JOptionPane.showInputDialog("Enter X coordinate for the first corner of the triangle: ");
double x1 = Double.parseDouble(input);
input = JOptionPane.showInputDialog("Enter Y coordinate for the first corner of the triangle: ");
double y1 = Double.parseDouble(input);
input = JOptionPane.showInputDialog("Enter X coordinate for the second corner of the triangle: ");
double x2 = Double.parseDouble(input);
input = JOptionPane.showInputDialog("Enter Y coordinate for the second corner of the triangle: ");
double y2 = Double.parseDouble(input);
input = JOptionPane.showInputDialog("Enter X coordinate for the third corner of the triangle: ");
double x3 = Double.parseDouble(input);
input = JOptionPane.showInputDialog("Enter Y coordinate for the third corner of the triangle: ");
double y3 = Double.parseDouble(input);
Triangle t = new Triangle(x1, x2, x3, y1, y2, y3);
System.out.println("Length A is: " + t.getLengthA());
System.out.println("Length B is: " + t.getLengthB());
System.out.println("Length C is: " + t.getLengthC());
System.out.println("Angle A is: " + t.getAngleA());
System.out.println("Angle B is: " + t.getAngleB());
System.out.println("Angle C is: " + t.getAngleC());
System.out.println("Area: " + t.getArea());
System.out.println("Perimeter: " + t.getPerimeter());
in.close();
}
}
You're showing JOptionPanes that prompt the user for input, but you're not getting the input and you're thus not using the input to set the state of your Triangle, creating a default Triangle object using its parameterless constructor. Understand that there's no magic in Java programming, and your Triangle object will not magically know what numbers the user has entered and change itself accordingly. Instead you must give that information into your Triangle.
What you must do is assign the results returned from the JOptionPanes, parse them into doubles, and then use those numbers to create a Triangle, using the constructor that takes numeric value parameters, not the default constructor. Do this, and you should be good.
e.g.
String input = JOptionPane.showInputDialog("Enter X coordinate for the first corner of the triangle: ");
double x1 = Double.parseDouble(input);
input = JOptionPane.showInputDialog("Enter Y coordinate for the first corner of the triangle:
double y1 = Double.parseDouble(input);
//.... etc repeat...
Triangle triangle = new Triangle(x1, x2, x3, y1, y2, y3);
Edit
This constructor ignores the values being passed in:
public Triangle(double x1, double x2, double x3, double y1, double y2, double y3)
{
x1 = 0;
x2 = 0;
x3 = 0;
y1 = 0;
y2 = 0;
y3 = 0;
}
A constructor like the one you'll need, should take the values passed in, and use those values to set class fields. For instance here:
public class Foo {
private int bar; // the bar field
public Foo(int bar) {
this.bar = bar;
}
}
Note that I use this.bar above so that Java knows that I want to set the bar field with the value held by the bar parameter (the bar without the this). You will need to do something similar only with 6 parameters, not one.
Then you do all your calculations in a separate block of code called an initializer block:
{
/**
* Find lengths of all sides
*/
lengthA = Math.pow(Math.pow((x2 - x1), 2) + Math.pow((y2 - y1), 2) * .05, lengthA);
lengthB = Math.pow(Math.pow((x3 - x2), 2) + Math.pow((y3 - y2), 2) * .05, lengthB);
lengthC = Math.pow(Math.pow((x1 - x3), 2) + Math.pow((y1 - y3), 2) * .05, lengthC);
}
This code gets called before your constructor, and so even if you set your Triangles fields correctly, this code wouldn't work. You don't want to use initializer blocks, and you can forget I even mentioned them other than to tell you not to use them. Instead do your calculations inside your constructor, and do so after setting all your fields.
Note that I've purposely not posted a solution to your problem because I firmly believe that what most of us need is to understand the concepts underlying any problems we are having, and then use that understanding to create our own code solutions.
Most important, read your texts, no better, study your texts, because the mistakes you're making involve foundational concepts, and show that you don't yet understand these concepts and have resorted to guessing. This will never work, as you need to understand all this and understand it well if you're going to be able to progress in this course.
Good luck!
Edit 2
For Tom, run this:
public class TestInitializerBlock {
public TestInitializerBlock() {
System.out.println("Inside of constructor");
}
{
System.out.println("Inside of initializer block");
}
public static void main(String[] args) {
new TestInitializerBlock();
}
}

Triangle class using an abstract shape class

So I have this triangle class I need to create using an abstract class. It will also be drawn by a tester class. I am part of the way through it but I am having serious issues with the math portion. I have set the coordinates in the tester class, I have no idea of how to get the pen to turn a certain degree to draw the next side of the triangle. Attached is all the classes and I have so far. Any help will be appreciated.
Tester class
import TurtleGraphics.*;
public class TestShapes1 {
public static void main (String[] args) {
// Declare and instantiate a pen, a circle and a wheel
Pen p = new StandardPen();
//Shape s1 = new Circle1 (20, 20, 20);
//Shape s2 = new Wheel1 (-20, -20, 20, 6);
Shape1 t2 = new Triangle1 (0, 0, 50, 0, 0, 30);
// Draw the circle and wheel
//s1.draw (p);
t2.draw (p);
}
}
Shape Class
import TurtleGraphics.Pen;
public interface Shape1 {
public double area();
public void draw (Pen p);
public double getXPos();
public double getYPos();
public void move (double xLoc, double yLoc);
public void stretchBy (double factor);
public String toString();
}
Triangle Class
import TurtleGraphics.Pen;
public class Triangle1 implements Shape1 {
private double x1, y1, x2, y2, x3, y3;
private double s1, s2, s3;
private double d1, d2;
//private double height, width;
public Triangle1() {
x1 = 0;
y1 = 0;
x2 = 1;
y2 = 0;
x3 = 0;
y3 = 1;
//height = 1;
//width = 1;
}
public Triangle1 (double xLoc1, double yLoc1, double xLoc2, double yLoc2, double xLoc3, double yLoc3) {
x1 = xLoc1;
y1 = yLoc1;
x2 = xLoc2;
y2 = yLoc2;
x3 = xLoc3;
y3 = yLoc3;
//height = h;
//width = w;
}
public double area() {
return (Math.abs(x1*y2-x2*y1+x2*y3-x3*y2+x3*y1-x1*y3))/2.0;
}
public void draw (Pen p) {
s1 = Math.sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2));
s2 = Math.sqrt((x2-x3)*(x2-x3)+(y2-y3)*(y2-y3));
s3 = Math.sqrt((x3-x1)*(x3-x1)+(y3-y1)*(y3-y1));
p.up();
p.move (x1, y1);
p.down();
p.setDirection (0);
p.move (s1);
d1 = (Math.acos((s2*s2+s3*s3-s1*s1)/(2.0*s2*s3)))*180/Math.PI;
p.turn (180 - d1);
p.move (s2);
d2 = (Math.acos((s3*s3+s1*s1-s2*s2)/(2.0*s3*s1)))*180/Math.PI;
p.turn (180 - d2);
p.move (s3);
p.turn (-90);
//p.move ();
}
public double getXPos() {
return x1;
}
public double getYPos() {
return y1;
}
public void move (double xLoc, double yLoc) {
x1 = x1 + xLoc;
y1 = y1 + yLoc;
x2 = x2 + xLoc;
y2 = y2 + yLoc;
x3 = x3 + xLoc;
y3 = y3 + yLoc;
}
public void stretchBy (double factor) {
x1 *= factor;
y1 *= factor;
}
public String toString() {
String str = "TRIANGLE\n";
// + "Width & Height: " + width + " & " + height +"\n"
// + "(X,Y) Position: (" + xPos + "," + yPos + ")\n"
// + "Area: " + area();
return str;
}
}
You don't need any math. Just pass the degrees to p.turn(). So use
p.turn(180);
instead of
d1 = (Math.acos((s2*s2+s3*s3-s1*s1)/(2.0*s2*s3)))*180/Math.PI;
p.turn (180 - d1);
See the documentation for reference:
The degrees can be an integer or floating-point number. Example:
pen.turn(-45); Rotate the pen 45 degrees clockwise.

Categories