I want to make it work to where I run ComplexTest.class and then in that class it runs Complex.class. I'm pretty new at java I have no idea what's wrong. Not sure why the compiler expects to see .class and a semi colon where it thinks they should be.
Main class
public class ComplexTest
{
//private final double re; // the real part
//private final double im; // the imaginary part
public static void main(String[] paramArrayOfString)
{
CreateObjs();
PrintHeader1();
PrintHeader2();
// invoke and Initialize a Complex object
Complex Comp = new Complex(); // Invokes Complex constructor (pg 315)
Comp.JunctionBox(CompA, CompB);
// multiply.printQuestionResult();
}
public static void CreateObjs()
{
Complex CompA = new Complex(9.5D, 7.7D);
Complex CompB = new Complex(1.2D, 3.1D);
}
public static void PrintHeader1()
{
System.out.printf(" A complex number in the \n form (x, y) is equal to \n x + yi, where i is \n square root of -1.\n");
}
public static void PrintHeader2()
{
System.out.printf("\n *-Complex numbers calculations-*");
}
}
2nd class
/******************************************************************************
* Data type for complex numbers.
*
* The data type is "imagmutable" so once you create and initialize
* a Complex object, you cannot change it. The "final" keyword
* when declaring re and imag enforces this rule, making it a
* compile-timage error to change the .re or .imag fields after
* they've been initialized.
*
* % java Complex
* a = 5.0 + 6.0i
* b = -3.0 + 4.0i
* b + a = 2.0 + 10.0i
* a - b = 8.0 + 2.0i
* a * b = -39.0 + 2.0i
* a / b = 0.36 - 1.52i
******************************************************************************/
public class Complex {
// Constants (final)
private final double re; // the real part
private final double imag; // the imaginaryinary part
// Variables
public double product;
// create a new object with the given real and imaginaryinary parts
public Complex(double real, double imaginary) {
re = real;
imag = imaginary;
}
// return a string representation of the invoking Complex object
public String toString() {
if (imag == 0) return "<" + re + ">";
if (re == 0) return "<" + imag + ">";
if (imag < 0) return "<" + re + " - " + (-imag) + ">";
return "<" + re + ", " + imag + ">";// + "i";
}
// return a new Complex object whose value is (this + b)
public Complex plus(Complex b) {
Complex a = this; // invoking object
double real = a.re + b.re;
double imaginary = a.imag + b.imag;
return new Complex(real, imaginary);
}
// return a new Complex object whose value is (this - b)
public Complex minus(Complex b) {
Complex a = this;
double real = a.re - b.re;
double imaginary = a.imag - b.imag;
return new Complex(real, imaginary);
}
// return a new Complex object whose value is (this * b)
public Complex timages(Complex b) {
Complex a = this;
double real = a.re * b.re - a.imag * b.imag;
double imaginary = a.re * b.imag + a.imag * b.re;
return new Complex(real, imaginary);
}
// return a new Complex object whose value is the reciprocal of this
public Complex reciprocal() {
double scale = re*re + imag*imag;
return new Complex(re / scale, -imag / scale);
}
// return the real or imaginaryinary part
public double re() { return re; }
public double imag() { return imag; }
// return a / b
public Complex divides(Complex b) {
Complex a = this;
return a.timages(b.reciprocal());
}
// sample client for testing
public static void main(String[] args) {
Complex a = new Complex(9.5, 7.7);
Complex b = new Complex(1.2, 3.1);
System.out.printf("a = %s\n", a);
System.out.println("b = " + b);
System.out.println("a + b = " + a.plus(b));
System.out.println("a - b = " + a.minus(b));
System.out.println("a * b = " + a.timages(b));
System.out.println("a / b = " + a.divides(b));
}
}
Compiler/Syntax errors:
ComplexTest.java:15: error: constructor Complex in class Complex cannot be applied to given types;
Complex Comp = new Complex(); // Invokes Complex constructor (pg 315)
^
required: double,double
found: no arguments
reason: actual and formal argument lists differ in length
ComplexTest.java:16: error: cannot find symbol
Comp.JunctionBox(CompA, CompB);
^
symbol: variable CompA
location: class ComplexTest
ComplexTest.java:16: error: cannot find symbol
Comp.JunctionBox(CompA, CompB);
^
symbol: variable CompB
location: class ComplexTest
3 errors
EDIT1: Fixed the junk class, updated the errors code block. I knew that the junk class was a problem.
EDIT2: I need more help, I am making more errors trying to fix the ones I already have.
You have a "junk" class declaration messing the file up.
public class JunctionBox() {
}
...is not a valid class declaration to begin with (the brackets should not be there), and you should only have a single public class declaration - with the class named as the file - in each Java file.
Removing that class declaration would make the file compile correctly.
The problem is due to having the concatenation of double and string you have to convert them first to string in every way possible
for example in the following way
change
if (imag == 0) return "<" + re + ">"
to
if (imag == 0) return "<" + String.valueOf(re) + ">"
Some errors are:
1) in the main method of ComplexTest you invoke the empty Constructor Complex() that you have not defined yet.
2) in the next line of code you use CompA and CompB object, but you have not defined them.
3) In the second file you first declare JunctionBox Class, but you put a main method method in a secodary class of the same file.
Correct first the above errors and the update you question.
Related
So I, have this code to trace and I had the results of 2.25 and 2.75. But when I compile it, I get 1.5 and 2.0. Why is that? Do the parentheses have anything to do with that?
public class TraceClass {
private double valBefore;
private double valAfter;
public TraceClass(double valIn) {
this.valBefore = valIn;
this.valAfter = 0.0;
}
public void doIt(boolean which){
if (which == true) {
this.valAfter = ((int) this.valBefore) + .5;
}
else {
this.valAfter = (int) (this.valBefore + .5);
}
}
public double getValAfter(){
return this.valAfter;
}
}
public class MainClass {
public static void main(String[] args) {
TraceClass traceObj = new TraceClass(1.75);
traceObj.doIt(true);
double temp = traceObj.getValAfter();
System.out.println("Result is " + temp);
traceObj.doIt(false);
temp = traceObj.getValAfter();
System.out.println("Result is " + temp);
}
}
edit: this is code that my teacher gave out ask practice for stack tracing. i got 2.25 because I added 1.75+.5= 2.25. But then I accidentally added .5 to 2.25 to get 2.75
edit2: typo
Both the parentheses and the casts to int affect the result, and the order matters.
For the true case, valBefore is casted to int first, yielding the integer value 1 (it is truncated). Then .5 is added, a double value, so 1 is widened to 1.0 and 1.5 results.
For the false case, valBefore is added to 0.5 first, and 1.5 + .5 is 2.0. Then that result is cased to int which yields 2. The assignment back to the double variable valAfter widens it back to double -- 2.0.
You are casting your variable to int for some strange reason which means you are adding 1 (integer part of 1.75) and 0.5 = 1.5 and in the second case you are casting the result of the addition to int so you get 1.5 + 0.5 = 2 (then casted to double again), so the second time you do not lose anything since the result happened to be an even integer.
Just remove all cast to int, it makes no sense when calculating with double values
When you cast the double value into an int, it just does not count the decimal parts. I just convert an int to double. you don't need to cast either.
import org.junit.jupiter.api.Test;
public class DoubleIssueStackOverflow {
#Test
public void test_first(){
TraceClass traceObj = new TraceClass(1.75);
traceObj.doIt(true);
double temp = traceObj.getValAfter();
System.out.println("Result is " + temp);
traceObj.doIt(false);
temp = traceObj.getValAfter();
System.out.println("Result is " + temp);
}
public class TraceClass {
private double valBefore;
private double valAfter;
public TraceClass(double valIn) {
this.valBefore = valIn;
this.valAfter = 0.0;
}
public void doIt(boolean which) {
if (which == true) {
this.valAfter = this.valBefore + .5;
} else {
this.valAfter = this.valBefore + .5;
}
}
public double getValAfter() {
return this.valAfter;
}
}
}
I'm Making a game which uses a parent to run an attack class as shown below
public String attack(int damage, int extradamage, String type) {
int hitpossibility;
hitpossibility = (int) ((Math.random() * 100) + 1);
if (type.compareTo("Ranged") == 0) {
weaponnoise = "twang!";
}else{
weaponnoise = "swing!";
}
if (chancetohit >= hitpossibility) {
for (int x = 0; x < damage; x++) {
result = result + (int) ((Math.random() * 6) + 1);
}
result = result + extradamage;
return weaponnoise + " The " + name + " did " + +result + " damage";
}
return weaponnoise +"The " +name+" missed!";
}
I have multiple different weapons which i want to use and have succeded in this however i have a dagger which i would like to attack twice per turn instead of once like the others. This is the class which i use to set the daggers damage values:
public class Dagger extends Blade {
public Dagger() {
super();
damage = 1;
extradamage = -1;
chancetohit = 75;
}
public String attack(int damage, int extradamage, String type) {
return super.attack(damage, extradamage, type);
}
I then have a class that runs it and currently it does this:
for (int l = 0; l < 2; l++) {
System.out.println(pointy.attack(pointy.damage, pointy.extradamage, pointy.getType()));
monsterhealth = monsterhealth - pointy.result;
System.out.println(monsterhealth);
pointy.result = 0;
}
Instead of it printing the attack twice, i want it to attack twice on the same line. I was wondering what i can change in the dagger class which would allow me to do so.
Any help is of course appreciated thank you!
This answer is an explanation of #Arnav 's comments. Here Dagger is a sub-class of the main weapon class and you want to invoke super-class' attack twice when the attack method of Dagger is called.
For this you need to call super.attack twice from Dagger attack method:
public class Dagger extends Blade {
public Dagger() {
super();
damage = 1;
extradamage = -1;
chancetohit = 75;
}
public String attack(int damage, int extradamage, String type) {
String result1 = super.attack(damage, extradamage, type);
String result2 =super.attack(damage, extradamage, type);
return // You can return result1 or result2 based on your requirement
}
Note: I deleted my earlier answer, because this approach is better than the other one.
The null-pointer exception error occurs in my toString method. I'm at a loss as to why. The error can occur through multiple ways. Most commonly, an object's reference is declared but the object itself remains uncreated. I've declared and created (is initialized the right word?) Mycircle circle1 = new Mycircle (); and Mypoint center = new Mypoint ();
I suspected that I hadn't initialized any of my fields when I invoked my getter methods, but that's not true. The setter methods work cleanly -- I've been successful in inputting values. Doesn't that imply that my getter methods can access some non-null value.
import java.util.Scanner;
public class MyCircle {
private Mypoint center;
private double radius;
Scanner input = new Scanner (System.in);
public MyCircle() {
radius = 0.0;
Mypoint center = new Mypoint ();
System.out.println("Enter coordinates here");
center.setCoordinateX(input.nextDouble());
center.setCoordinateY(input.nextDouble());
}
public String toString(MyCircle object) {
return "Circle # " + "(" + object.center.getCoordinateX() + "," +
object.center.getCoordinateY() + ")" + ". Its radius is " +
object.radius;
}
public double calcArea(MyCircle object) {
double area = Math.pow(object.radius, 2) * Math.PI;
return area;
}
public static void main (String[]args) {
MyCircle circle1 = new MyCircle ();
circle1.radius = 3.0;
System.out.println(circle1.calcArea(circle1));
System.out.println(circle1.toString(circle1));
}
}
class Mypoint {
private double posX;
private double posY;
public void setCoordinateX(double x) {
posX = x;
}
public void setCoordinateY(double y) {
posY = y;
}
public double getCoordinateX() {
return posX;
}
public double getCoordinateY() {
return posY;
}
}
In your MyCircle constructor, you're creating a local variable called center here:
Mypoint center = new Mypoint ();
What you probably want is to initialize the instance member:
center = new Mypoint ();
Your code doesn't make much sense, presumably this
public String toString(MyCircle object)
{
return "Circle # " + "(" + object.center.getCoordinateX() + ","
+ object.center.getCoordinateY() + ")"
+ ". Its radius is " + object.radius;
}
Should be
#Override
public String toString() {
return "Circle # (" + center.getCoordinateX() + ","
+ center.getCoordinateY()
+ "). Its radius is " + radius;
}
Then let's fix your constructor, use this so you know you're updating the instance field (instead of shadowing it) -
public MyCircle() {
this.radius = 0.0;
this.center = new Mypoint(); // <-- this.center
System.out.println("Enter coordinates here");
this.center.setCoordinateX(input.nextDouble());
this.center.setCoordinateY(input.nextDouble());
}
First of all, your toString() method is untypical. You want a Circle#toString() with no argument and produce a print representaton of yourself (i.e. this instead of object=).
Your toString method can fail if:
object is null
object.center is null
object.center.getCoordinateX() or getCoordinateY() itself throws exception.
The later case would be visible in the stacktrace, the other two cases all show the same line number as the cause.
It looks like the second case is your problem (as you fill a local variable and not the field of MyCircle).
BTW: using a input scanner in a constructor is a horrible layering violation. You should seperate input/output/user interaction logic from the geometric (circly, point) classes.
There are many things wrong in your code beside what #Mike pointed out.
Getting input from the user within the constructor is bad. You should get the input in the main method, and pass it to the constructor. In addition, you don't initialize the radius. It remains 0.0.
The constructor call should look like this (the MyPoint object passed to the constructor should be initialized prior to calling the constructor) :
MyCircle circle1 = new MyCircle (center, radius);
The constructor should look like this :
public MyCircle(MyPoint center, double radius)
{
this.radius = 0.0;
this.center = center;
}
The toString and calcArea methods don't need a parameter. They should operate on the current object (this) :
public String toString()
{
return "Circle # " + "(" + this.center.getCoordinateX() + "," + this.center.getCoordinateY() + ")" + ". Its radius is " + this.radius;
}
Sorry for what is probley a simple question but how would i go about setting up a toString() method for an array list?
is it as simple as
points = new ArrayList<Point>();
public String toString() {
return points.toString();}
which does not seem to be working for me, or would it be more complex since it is a array list? Because for some reason when i execute mine like this its only printing the first value or object.
P.S I'm trying to return all the values that i have already added to my list.
More in detail
constructer
public Cloud() {
points = new ArrayList<Point>();
}
add point
public void addPoint(Point p) { // done
if (points.contains(p)) {
// if p is already in the list it does nothing
} else {
points.add(p); // if p was not in the list it adds it to the end
}
}
toString
public String toString() {
return points.toString();
}
main
public static void main(String[] args) {
Cloud cloud = new Cloud();
cloud.setDebug(false);
System.out.println("cloud.debug OFF");
System.out.println("initial cloud: " + cloud.toString());
Point p1 = new Point(3.0, 1.0);
cloud.addPoint(p1);
Point p2 = new Point(2.0, 2.0);
cloud.addPoint(p2);
Point p3 = new Point(1.5, 1.5);
cloud.addPoint(p3);
Point p4 = new Point(3.0, 0.0);
cloud.addPoint(p4);
System.out.println("final cloud: " + cloud);
This is just printing final cloud: (3.0,1.0) while it should be printing final cloud: [(3.0,1.0), (2.0,2.0), (1.5,1.5), (3.0,0.0)]
edit: Points class
public class Point {
private double x;
private double y;
public static final double EPSILON = 1e-5;
public static boolean debug = false;
public Point(double x, double y) {
this.x = x;
this.y = y; // Done sets the x,y private types to the x,y type provided
// in the ()
}
public Point() {
this(0.0, 0.0); // calls the point (double x,double) constructer with
// the given arguments
} // inturn setting x and y == 0.0
public double getX() {
return x; // returns the private value of x when called in the main
// method
} // so it can't be changed by the user
public double getY() {
return y; // return the private value of y when called in the main
// method so it can't be changed
} // by the user
public String toString() {
return "(" + x + "," + y + ")"; // done by teacher sets the toString
// method and implemetns it
}
public boolean equals(Point p) {
if (Math.abs(this.getX()) - Math.abs(p.x) < EPSILON) {
return true; // checks if x - p.x is less than epsilon which covers
// the round off
}
if (Math.abs(this.getY()) - Math.abs(p.y) < EPSILON) {
return true; // checks if y-p.y is less than epsilon which covers
// the round off
}
return false; // both these methods test for equality using epsilon,
// becuae we are dealing with
} // doubles, so roundof can occur
public boolean equals(Object obj) { // this was given to us
if (obj instanceof Point) {
Point p = (Point) obj; // This method overrides the object equals
// method and the calls
return equals(p); // the clas's equals(point) method
}
return false;
}
// TODO Implement Point.euclidDist
/**
*
* #param p
* #return Euclidean distance of this point to point p
*/
public double euclidDist(Point p) {
double distance = 0;
double firstvalue;
double secondvalue;
distance = Math.sqrt(((this.getX() - p.x) * (this.getX() - p.x)) // calculate
// the
// distance
+ ((this.getY() - p.y) * (this.getY() - p.y))); // between the
// two points
// firstvalue= Math.pow(this.getX()-p.x, 2);
// secondvalue= Math.pow(this.getY()-p.y, 2);
// distance = Math.sqrt(firstvalue + secondvalue);
return distance;
}
/**
* #param args
* : no args
*/
public static void main(String[] args) {
// test all methods
if (debug)
System.out.println("debug ON");
else
System.out.println("debug OFF");
System.out.println("EPSILON: " + Point.EPSILON);
Point origin = new Point();
Point p1 = new Point(0.0, 4.0);
Point p2 = new Point(3.0000001, 3.9999999);
Point p3 = new Point(3.0, 4.0);
Point p4 = new Point(0.0, 5.0);
Point p5 = new Point(12.0, 0.0);
System.out.println("origin: " + origin);
System.out.println("p1: " + p1);
System.out.println("p2: " + p2);
System.out.println("p3: " + p3);
System.out.println("p4: " + p4);
System.out.println("p5: " + p5);
if (p2.equals(p3))
System.out.println(p2 + " equals " + p3);
else
System.out.println(p2 + " does not equal " + p3);
System.out.println("Euclidean distance between " + origin + " and "
+ p1 + ": " + origin.euclidDist(p1));
System.out.println("Euclidean distance between " + p1 + " and " + p3
+ ": " + p1.euclidDist(p3));
System.out.println("Euclidean distance between " + p3 + " and "
+ origin + ": " + p3.euclidDist(origin));
System.out.println("Euclidean distance between " + p4 + " and " + p5
+ ": " + p4.euclidDist(p5));
}
}
You can only create toString() method overrides in classes of yours, not in other classes that you're not overriding. ArrayList already has a valid toString() method that is useful. You will just need to make sure that the items held by the List are from a class that also has a valid toString() method.
Note you state:
which does not seem to be working for me...
Because for some reason when i execute mine like this its only printing the first value or object.
This suggests that you don't have a toString() problem, but that you actually have another completely different problem with your program, that you're not adding objects to the list correctly. You need to do more debugging and show more pertinent code.
Edit
I'm guessing that your Point class's contains(...) method is erroneous, that it is returning true when it should be returning false. Please show us the Point class.
Edit 3 (deleted edit 2)
Your equals is wrong:
This is OK:
public boolean equals(Object obj) { // this was given to us
if (obj instanceof Point) {
Point p = (Point) obj; // This method overrides the object equals
// method and the calls
return equals(p); // the clas's equals(point) method
}
return false;
}
But here, you return equals if either x's or y's closely match and that shouldn't be. You should only return true if BOTH closely match:
public boolean equals(Point p) {
if (Math.abs(this.getX()) - Math.abs(p.x) < EPSILON) {
return true; // checks if x - p.x is less than epsilon which covers
// the round off
}
if (Math.abs(this.getY()) - Math.abs(p.y) < EPSILON) {
return true; // checks if y-p.y is less than epsilon which covers
// the round off
}
return false; // both these methods test for equality using epsilon,
// becuae we are dealing with
} // doubles, so roundof can occur
Also you're using Math.abs(...) incorrectly. It should go around the subtraction statement, not around each variable.
I have been trying and trying for a while with this and I just seem to cannot solve it.
I am supposed to extract classes from a Java-file and print in a shape UML-diagram, in the IDE or writing on a file
e.g the program
public class Complex {
private int re;
private int im;
public Complex(int re, int im) {
this.re = re;
this.im = im;
}
public Complex add(Complex h) {
return new Complex(this.re + h.re, this.im + h.im);
}
public Complex sub(Complex h) {
return new Complex(this.re - h.re, this.im - h.im);
}
public Complex mul(Complex h) {
int a = re;
int b = im;
int c = h.re;
int d = h.im;
return new Complex(a * c - b * d, b * c + a * d);
}
public Complex div(Complex h) {
int a = re;
int b = im;
int c = h.re;
int d = h.im;
return new Complex((a * c + b * d) / (c * c + d * d), (b * c - a * d)
/ (c * c + d * d));
}
public String toString() {
if (im >= 0) {
return re + " + " + im + "i";
} else
return re + " " + im + "i";
}
}
Should generate something like:
a Complex
b int re
b int re
a Complex(re:int, im:int)
a add():Complex
a sub():Complex
a mul():Complex
a div():Complex
a toString():String
a main()
I have started with stripping the first parenthesis from the file;
import java.io.*;
public class ClassExtract {
public static void main(String[] args) {
ClassExtract obj = new ClassExtract();
obj.removeBracket("Complexx.txt");
}
public void removeBracket(String filnamn) {
try {
File f = new File(filnamn);
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
FileWriter fw = new FileWriter("noparanthesis_" + filnamn);
BufferedWriter bw = new BufferedWriter(fw);
String rad = br.readLine();
while (rad != null) {
rad = rad.replaceAll("\\(", " ");
bw.write(rad);
bw.newLine();
rad = br.readLine();
}
bw.close();
br.close();
} catch (FileNotFoundException e) {
System.out.printf("The file " + filnamn + " was not found.");
} catch (IOException e) {
System.out.printf("Writing error.");
}
}
}
I have thought of different ways of approaching this problem. The way that I think would be easiest would be to strip everything after collected the head public class Complex, which would mean the rest of the file would look something like:
public Complex int re, int im
public Complex add Complex h
public Complex sub Complex h
etc and do the same and read the index of the lines.
I actually feel very lost and I have hard to tackle this problem, any help would really be appreciated.
As Qwe says in the comment, you would be much better off looking at the Java Reflection APIs.
These let you inspect a class and list its methods, superclasses, interfaces and so on.
By tackling this problem with regexes/text analysis, you are basically trying to write a partial Java parser, which is an entirely unnecessary amount of pain!