please my question are two and very simple
misinterpret enum as is
this idea missing some important abstraction in my code
code example, where oprt.calc(x, y) isn't compilable, with warning cannot find symbol
public enum Operation {
PLUS {
public double calc(double x, double y) {
return x + y;
}
},
MINUS {
public double calc(double x, double y) {
return x - y;
}
},
MULTILPLE {
public double calc(double x, double y) {
return x * y;
}
},
DIVIDED_BY {
public double calc(double x, double y) {
return x / y;
}
};
public static void main(String args[]) {
double x = 15.25;
double y = 24.50;
for (Operation oprt : Operation.values()) {
System.out.println(x + " " + oprt + " "
+ y + " = " + oprt.calc(x, y));
}
}
}
What you miss is abstract declaration of calc() method:
enum Operation {
PLUS {
public double calc(double x, double y) {
return x + y;
}
},
MINUS {
public double calc(double x, double y) {
return x - y;
}
},
MULTILPLE {
public double calc(double x, double y) {
return x * y;
}
},
DIVIDED_BY {
public double calc(double x, double y) {
return x / y;
}
};
**public abstract double calc(double x, double y);**
public static void main(String args[]) {
double x = 15.25;
double y = 24.50;
for (Operation oprt : Operation.values()) {
System.out.println(x + " " + oprt + " "
+ y + " = " + oprt.calc(x, y));
}
}
}
You need to declare an abstract method double calc(double x, double y) in the enum directly, and override it in every enum member.
The correct syntax to use enum methods is:
private enum Operation {
PLUS, MINUS, MULTILPLE, DIVIDED_BY;
public double calc(double x, double y) {
switch (this) {
case PLUS:
return x + y;
case MINUS:
return x - y;
case MULTILPLE:
return x * y;
case DIVIDED_BY:
return x / y;
}
return 0;
}
}
public static void main(String args[]) throws IOException {
double x = 15.25;
double y = 24.50;
for (Operation oprt : Operation.values()) {
System.out.println(x + " " + oprt + " " + y + " = "
+ oprt.calc(x, y));
}
}
You are overriding calc(), while you have no original calc() method. Either declare an abstract method:
public abstract double calc(double x, double y);
or declare a concrete method with a default implementation:
public double calc(double x, double y)
{
// ...
}
It doesn't compile because currently, the calc method only exists in each of the possible values of your enum - but it does not exist on the type Operation itself. That's why your compiler (and mine) doesn't accept it.
So, you need to define the method in the type. Maybe something like this:
public abstract double calc(double x, double y);
Your enum values (PLUS, MINUS, MULTIPLE and DIVIDED_BY each implement that method.
public double calc(double x, double y){}
is same as
private double calc(double x,double y){}
unless you add calc() method to the enum Operation.As per JLS:
Instance methods declared in these class bodies are may be invoked outside
the enclosing enum type only if they override accessible methods in
the enclosing enum type.
So basically , the type of oprt is Operation and as Operationdoesn't have any declaration for method called double calc(double x,double y), you cannot invoke the method using oprt. In short the methods defined in class bodies should be overridden methods, for them to be accessible outside.
Related
I've been trying to make a calculator with multiple classes, however I am not that experienced with classes. I've been having a few problems with it.
This is the user input section, doesn't seem to have any problems
import java.util.Scanner;
public class GetData
{
Scanner getdata = new Scanner(System.in);
public double intx;
public double inty;
public void getInt() {
System.out.print("Enter a number");
double intx = getdata.nextDouble();
}
public void getDouble() {
System.out.print("Enter a double");
double inty = getdata.nextDouble();
}
}
This is the operation section, the most problems are happening here, as said in the error there are missing error statements,
import java.util.Scanner;
public class MathOps {
Scanner mathops = new Scanner(System.in);
public double x;
public double y;
public double answer;
public double add(int x, int y) {
System.out.println("Adding " + x + "and " + y);
return x + y;
}
public double multiply(int x, int y) {
System.out.println("Multiplying " + x + "and " + y);
return x * y;
}
public double sub(int x, int y) {
System.out.println("Subtracting " + x + "and " + y);
if(x >= y) {
return x - y; }
if(y >= x) {
return y - x; }
}
public double divide() {
System.out.println("Dividing " + x + "and " + y);
if(x >= y) {
return x / y; }
if(y >= x) {
return y / x; }
}
}
----jGRASP exec: javac -g MathOps.java
MathOps.java:27: error: missing return statement
}
^
MathOps.java:35: error: missing return statement
}
^
2 errors
----jGRASP wedge2: exit code for process is 1. ----jGRASP: operation
complete.
This is were I'm putting it all together, also has problems
import java.util.Scanner;
public class L3Operations
{
int geti;
int getd;
public static void main(String[] args)
{
//instatnate
Scanner a = new Scanner(System.in);
int x1 = a.getInt();
}
}
As an aside, note that x >= y and y >= x will both be false if either x or y is Double.NaN, and you can enter NaN as a double value with the Scanner class (and also Infinity and -Infinity). So unless you check the values ahead of time to rule out NaN, you can't assume that at least one of those two conditions will be true.
You also can't assume that if x > y and y > x are false, then x == y, because for NaN all of those are false. And, if you have just assigned x = y, you can't assume that x == y, since if y was NaN that will be false.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I have created the following Java program. Its basic functionality is to perform addition, subtraction, multiplication, division and modular division on two numbers.
I have implemented the concept of object-oriented programming, but it is missing encapsulation.
How do I introduce encapsulation in it?
My code is:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* #author piyali
*/
public class Calculator {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
int x, y;
x = 13;
y = 5;
calculation add = new calculation();
calculation sub = new calculation();
calculation mul = new calculation();
calculation div = new calculation();
calculation mod = new calculation();
int addResult = add.addition(x, y);
int subResult = sub.subtraction(x, y);
int mulResult = mul.multiplication(x, y);
int divResult = mul.division(x, y);
int modResult = mod.modularDivision(x, y);
System.out.println("The addition of the numbers is " +addResult);
System.out.println("The subtraction of the two numbers is " +subResult);
System.out.println("The multiplication of the two numbers is " + mulResult);
System.out.println("The division of the two numbers is " +divResult);
System.out.println("The modular division of the two numbers is " + modResult);
}
}
class calculation {
int addition(int x, int y){
int z;
z = x + y;
return(z);
}
int subtraction(int x, int y){
int z;
z = x - y;
return(z);
}
int multiplication(int x, int y){
int z;
z = x * y;
return(z);
}
int division(int x, int y){
int z;
z = x / y;
return(z);
}
int modularDivision(int x, int y){
int z;
z = x % y;
return(z);
}
}
Well if you want true OOP and encapsulation, then create interface Calculation which has a method int calculate().
public interface Calculation {
int calculate();
}
Now create classes which implements this interface such as Addition or Subtraction etc.
public class Addition implements Calculation {
private final int x;
private final int y;
public Addition(int x, int y) {
this.x = x;
this.y = y;
}
#Override
public int calculate(){
return x + y;
}
}
Main method
public static void main(String[] args) {
int x, y;
x = 13;
y = 5;
Calculation add = new Addition(x, y);
System.out.println(add.calculate());
}
Advantages of such design is that if you will want to add any extra mathematical operations such as root, percentage or even derivation, you will not need to modify any implementation of class. Just write extra class which implements Calculation.
I don't think there's much to encapsulate here. This looks like it wants to be a basic math library, and since it has no data members, or helper functions, you can't do a whole lot here to encapsulate.
Since creating an instance of this class is a bit silly (see the Java Math library for example), make the methods static, and make the constructor private.
I guess not a form of encapsulation, but some design tips: You should make variables you aren't modifying final. You should also remove all unnecessary variables if you aren't using them. They aren't doing anything for readability, and they're just using extra blocks of memory (unless the JVM optimizes them out).
Improved code:
class calculation {
private calculation() {
throw new RuntimeException("Don't instantiate a math library!");
}
public static int addition(final int x, final int y){
return x + y;
}
public static int subtraction(final int x, final int y){
return x - y;
}
public static int multiplication(final int x, final int y){
return x * y;
}
public static int division(final int x, final int y){
return x / y;
}
public static int modularDivision(final int x, final int y){
return x % y;
}
}
By doing this, now you can call your calculation library with something like this:
int additionResult = calculation.addition(5, 5);
System.out.println(additionResult);
Use the concept of getter and setter.
class Calculator{
private int x, y, z;
void setValue(int a, int b){
x=a;
y=b;
}
int getValue(){
return z;
}
void addition(){
z=x+y;
}
void subtraction(){
z=x-y;
}
void multiplication(){
z=x*y;
}
void division(){
z=x/y;
}
void modDivision(){
z=x%y;
}
}
public class CalculatorTestDrive {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int num1, num2, result;
num1=13;
num2=5;
Calculator add = new Calculator();
Calculator sub = new Calculator();
Calculator mul = new Calculator();
Calculator div = new Calculator();
Calculator mod = new Calculator();
add.setValue(num1, num2);
add.addition();
result = add.getValue();
System.out.println("The addition of " + num1 + " and " + num2 + " is " +result);
sub.setValue(num1, num2);
sub.subtraction();
result = sub.getValue();
System.out.println("The subtraction of " + num1 + " and " + num2 + " is " +result);
mul.setValue(num1, num2);
mul.multiplication();
result = mul.getValue();
System.out.println("The multiplication of " + num1 + " and " + num2 + " is " +result);
div.setValue(num1, num2);
div.division();
result = div.getValue();
System.out.println("The division of " + num1 + " and " + num2 + " is " +result);
mod.setValue(num1, num2);
mod.modDivision();
result = mod.getValue();
System.out.println("The modular division of " + num1 + " and " + num2 + " is " +result);
}
}
I am trying to create a function which makes a random asteroid with (x, y, velocity x, velocity y) values of type BasicAsteroid, this is the constructor and function which creates a random asteroid:
private double x, y;
private double vx, vy;
public BasicAsteroid(double x, double y, double vx, double vy) {
this.x = x;
this.x = y;
this.vx = vx;
this.vy = vy;
}
public static BasicAsteroid makeRandomAsteroid() {
Random rand = new Random();
BasicAsteroid x = new BasicAsteroid((rand.nextInt()%FRAME_WIDTH), (rand.nextInt()%FRAME_HEIGHT), (rand.nextInt()%MAX_SPEED), (rand.nextInt()%MAX_SPEED));
System.out.println(x);
return x;
}
However this is the output when I create the asteroid:
game1.BasicAsteroid#6773120a
game1.BasicAsteroid#4261b6b3
game1.BasicAsteroid#2673b915
game1.BasicAsteroid#113eb90b
game1.BasicAsteroid#1abcc522
How can I output the values instead of the class#hashcode?
Thanks.
Overwrite the toString() method
#Override
public String toString(){
return "Asteroid at "+x+" "+y+" velocity "+vx+" "+vy;
}
You need to override the method toString() on your class.
#Override
public String toString(){
return "x: "+this.x+"y: "+this.y+"vx: "+this.vx+"vy: "+this.vy
}
In java, when you print an object, its toString() method is invoked to create the string that will be printed. What you're seeing here is the output of the default toString method. If you want to print the values nicely, add a function like this:
#Override
String toString(){
return "Asteroid with coords: (" + x + ", " + y + "), velocity: (" + vx + ", " + vy + ")";
}
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
Playing with a simple Java Point class where I would like to constrain the X and Y values to be doubles that must be in the range -10 to 10, inclusive. I've written some code, but it's been years since I've written java and I would like to know if this is how it would be written in modern Java:
public class Point {
private double x;
private double y;
public Point(double x, double y) {
constrain("x", x);
constrain("y", y);
this.x = x;
this.y = y;
}
// is there a cleaner/shorter way of handling this, such as a direct way of declaring a
// subtype of double that I could use in method signatures?
protected static void constrain(String name, double val) {
if ( val < -10 || val > 10 ) {
throw new IllegalArgumentException(name + " must be between -10 and 10");
}
}
public double getX() { return x; }
public void setX(double x) {
constrain("x", x);
this.x = x;
}
public double getY() { return y; }
public void setY(double y) {
constrain("y", y);
this.y = y;
}
#Override
public String toString() {
return ("[" + x + "," + y + "]");
}
}
This is probably how I'd do it:
public class Point
{
private static final double X_MIN = -10.0, X_MAX = 10.0;
private static final double Y_MIN = -10.0, Y_MAX = 10.0;
private double x, y;
public Point(double x, double y) throws IllegalArgumentException
{
setX(x);
setY(y);
}
public double getX()
{
return x;
}
public double getY()
{
return y;
}
public void setX(double x) throws IllegalArgumentException
{
if (x < X_MIN || x > X_MAX)
{
throw new IllegalArgumentException("X out of range.");
}
this.x = x;
}
public void setY(double y) throws IllegalArgumentException
{
if (y < Y_MIN || y > Y_MIN)
{
throw new IllegalArgumentException("Y out of range");
}
this.y = y;
}
#Override
public String toString()
{
return String.format("[%.1f,%.1f]", x, y);
}
}
If the X and Y values are always from the same domain then you could encapsulate them in a class that does the checking for you:
class Coord {
private final double scalarValue;
public Coord(double scalarValue) throws IllegalArgumentException {
if (Math.abs(scalarValue) > MAX_COORD) {
throw new IllegalArgumentException("Coordinate out of range");
}
this.scalarValue = scalarValue;
}
public double getScalar() {
return scalarValue;
}
}
That puts the check in one place and allows you to expand coordinate functionality in the future without messing up your Point class. It also explicitly makes coordinates immutable which is likely to be a good idea (depending on use case).
Then your point constructor becomes:
public Point(Coord x, Coord y);
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I can't seem to get my transform method right. Any suggestions on how I could make the method translate the point better? i.e. when this method is invoked, it should be able to give the new point. Also I'm having issues creating the slope method...I know slope is y2-y1/x2-x1 but how would I make that into a method. Is there a Math class I can import for the slope? Thanks much appreciated
import java.util.*;
public class Point {
private int x; // to store variables for x & y
private int y;
private double slope;
//default constructor
public Point () {
double x = 0;
double y = 0;
}
//alternate constructor
public Point (double x1, double y1) {
double x = x1;
double y = y1;
}
//set coordinates
public void setCoord (double x1, double y1){
double x = x1;
double y = y1;
}
//print method
public void print () {
System.out.print(x + "," + y);
}
//toString Method
public String toString() {
return "(" + x + "," + y + ")";
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public void equals () {
if (x==y)
System.out.println(" Coordinates are the same ");
else {
System.out.println(" Coordinates are different ");
}
}
public void copy(Point temp) {
x=temp.x;
y=temp.y;
}
public Point getCopy() {
Point temp = new Point();
temp.x = x;
temp.y = y;
return temp;
}
public void distanceFromOrigin(int x1, int y1) {
double dx = x-x1;
double dy = y-y1;
}
//calculate the distance from one point to another
public void distance (double x1, double y1) {
double distance = Math.sqrt((x * x1) + (y * y1));
}
//shift the location of a point by a given amount
public void transform (double dx, double dy) {
double transform = ((x+dx) (y+dy));
}
// returns true if any given point lines up horizontally with a given point.
public boolean isHorizontal () {
return true;
}
// returns true if any given point lines up vertically with a given point.
public boolean isVertical () {
return true;
}
// returns the slope of the line
public double slope() {
return slope;
}
}
public void equals (Object o) {
if(o instanceof Point) {
Point p = (Point)o;
return p.x == x && p.y == y;
} else {
return false;
}
}
public Point getCopy() {
return new Point(x, y);
}
public double slope(Point otherPoint) {
return ((double)(otherPoint.y - y)) / ((double)(otherPoint.x / x));
}
public double distance (Point otherPoint) {
double dx = otherPoint.x - x;
double dy = otherPoint.y - y;
return Math.sqrt((dx * dx) + (dy * dy));
}
public double distanceFromOrigin() {
return distance(new Point(0, 0));
}
public boolean isHorizontal (Point otherPoint) {
return otherPoint.y == y;
}
public boolean isVertical(Point otherPoint) {
return otherPoint.x == x;
}
public void transform (double dx, double dy) {
x += dx;
y += dy;
}