So I'm trying to make a program where you put in a radius and it spits out the area, diameter etc. but whenever I run the app it crashes. Here's what I've got if anyone can help that would be much appreciated
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
MeasureC[] mc = new MeasureC[5];
int i=0;
int p =5;
for(i=0;i<=p;i++)
{
System.out.println("What do you want the radius to be?");
double UserRad = scan.nextDouble();
mc[i].setRadius(UserRad);
mc[i].setArea();
mc[i].setDiameter();
mc[i].setCircumfrence();
System.out.println(mc[i].getRadius());
System.out.println(mc[i].getArea());
System.out.println(mc[i].getDiameter());
System.out.println(mc[i].getCircumfrence());
}
Here's the second class:
public class MeasureC {
private double radius, area, diameter, circumfrence;
public double getRadius() {
return radius;
}
public void setRadius(double newRadius) {
radius = newRadius;
}
public double getArea() {
return area;
}
public void setArea() {
area = 3.14*radius;
}
public double getDiameter() {
return diameter;
}
public void setDiameter() {
diameter = 2*radius;
}
public double getCircumfrence() {
return circumfrence;
}
public void setCircumfrence() {
circumfrence = 3.14*(2*radius);
}
MeasureC[] mc = new MeasureC[5];
This doesn't create an array of 5 MeasureC objects, it just allocates the space for them in memory. So, currently, every index points to null. That means that in your for loop when you try and access a particular element in your array you will get an error as .setRadius() etc... is not a method of null:
mc[i].setRadius(UserRad); // mc[i] is null
So, to fix this issue, you can create a new instance of your MeasureC class at each iteration and set it at your index:
for(i = 0; i < p; i++) { // set to i < p as max index in your array is 4 (not 5)
mc[i] = new MeasureC();
// code...
}
Replace:
for(i=0;i<=p;i++)
by:
for(i=0;i<p;i++)
as now you iterate 6 times on 5 dimension array and got ArrayIndexOutOfBoundsException
I assume you get a NullPointerException at the line mc[i].setRadius(UserRad);.
Think about what that means. Then it should be obvious what line you have to add before that to fix the problem.
Hint: Think about how Java does array initializations.
Assuming you want the radius to be the only input data allowed, we can try refactoring your code as (see notes below):
public class MeasureC {
private double radius, area, diameter, circumference;
public MeasureC (double radius) {
diameter = 2.0d * radius;
circumference = Math.pi * diameter;
area = Math.pi * Math.pow(radius, 2);
}
public double getRadius(){
return radius;
}
public double getArea(){
return area;
}
public double getDiameter(){
return diameter;
}
public double getCircumfrence(){
return circumfrence;
}
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int p = 5;
MeasureC[] mc = new MeasureC[p];
for (int i=0; i <= p; i++) {
System.out.println("What do you want the radius to be?");
double userRad = scan.nextDouble();
mc[i] = new Measure(userRad);
System.out.println(mc[i].getRadius());
System.out.println(mc[i].getArea());
System.out.println(mc[i].getDiameter());
System.out.println(mc[i].getCircumfrence());
}
}
Notes:
I expose a single constructor in your MeasureC class which accepts an input radius as a double. Inside that constructor I compute, using that input radius, the diameter, circumference, and area.
Since you only want the circle to be configurable via the radius, I removed setters for the diameter, circumference, and area.
A problem you had in your main() method was that you were not instantiating your MeasureC instances with new. I am doing this now.
Java naming conventions say that variable names should begin with lowercase letters, while class names begin with uppercase. Both are camelcase for subsequent letters. You should stick with this convention.
I am having a problem with abstract classes, the code runs but it won't take any value , it prints "0.0" everywhere, I'm thinking it is an acces problem.I have to make an abstract base class called "Point" where i declare the 3 coordinates of a point, then i have to calculate the area , volume and center point of a cube and a sphere .Also if something doesn't look good, needs formating, or don't understand a word, please tell me.Thank you.
//this is the base class
public abstract class Punct
{
public double x,y,z;
Punct(double x,double y, double z)
{
this.x=x;
this.y=y;
this.z=z;
}
public double getX()
{
return x;
}
public double getY()
{
return y;
}
public double getZ()
{
return z;
}
}
Then the sphere
//This is the sphere class that extends the Point class
public class Sfera extends Punct
{
private double aria,volumul,raza,centrul;
Sfera(double x, double y, double z,double aria,double volumul,
double centrul,double raza)
{
super(x, y, z);
this.aria=aria;
this.volumul=volumul;
this.centrul=centrul;
this.raza=raza;
}
public double getRaza(Punct p1,Punct p2)
{
raza=Math.sqrt(Math.pow(p2.x-p1.x,2)+Math.pow(p2.y-p1.y, 2)+Math.pow(p2.z-p1.z, 2));
return raza;
}
public double getAria()
{
aria=4*Math.PI*raza*raza;
return aria;
}
public double getVolumul()
{
volumul=4/3*Math.PI*raza*raza*raza;
return volumul;
}
public double getCentrul(Punct p1)
{
return centrul;
}
}
The Cube
//this is the cube
public class Cub extends Punct
{
double latura,aria,volumul,centrul;
Cub(double x, double y, double z,double latura, double aria,double volumul, double centrul)
{
super(x, y, z);
this.latura=latura;
this.aria=aria;
this.volumul=volumul;
this.centrul=centrul;
}
public double getLatura(Punct p1,Punct p2)
{
latura=Math.sqrt(Math.pow(p2.x-p1.x,2)+Math.pow(p2.y-p1.y, 2)+Math.pow(p2.z-p1.z, 2));
return latura;
}
public double getAria()
{
aria=6*Math.pow(latura, 2);
return aria;
}
public double getVolumul()
{
volumul=latura*latura*latura;
return volumul;
}
}
And the Test Class where i have the main
//this is the Test class
public class TestTema
{
public static void main(String[] args_)
{
Punct p1=new Punct(2, 2, 2) {};
Sfera obSfera=new Sfera(1,2,3,1,1,1,1);
System.out.println("Raza sfera:" + obSfera.getRaza(p1,p1));
System.out.println("Aria sfera=" + obSfera.getAria());
System.out.println("Volum sfera= " +obSfera.getVolumul());
// System.out.println("Centrul= "+obSfera.getSuprafata());
Cub obCub=new Cub(1,2,3,1,1,1,1);
System.out.println("Lungime latura cub:"+obCub.getLatura(p1,p1));
System.out.println("Aria cubului="+obCub.getAria());
System.out.println("Volumul cubului="+obCub.getVolumul());
// System.out.println("Suprafata="+obCub.getCentrul());
}
}
Your design is really wrong. Sfera has a method getRaza() that computes the distance between two points. There's no reason to use a Sphere to compute the distance betwwen two points. This should be an instance method of Punct, that should take another point as argument.
But there's worse: instead of just computing the distance between two points, it stores this distance in the Sphere, overwriting its previous raza (not sure why a sphere has a distance):
raza=Math.sqrt(Math.pow(p2.x-p1.x,2)+Math.pow(p2.y-p1.y, 2)+Math.pow(p2.z-p1.z, 2));
You made the same mistake in several other methods: get methods should not change the state of the object.
Now, let's see your code. You start by calling
obSfera.getRaza(p1,p1)
That computes the distance between p1 and itself, so the answer is 0, and this distance is stored in the Sphere (as explained above). So, after this line of code, you've set the sphere's raza to 0. You then execute
obSfera.getAria()
and this method does
aria=4*Math.PI*raza*raza;
return aria;
so, once again, instead of just returning the area of the sphere, it overwrites its area with the computed value, which is 0 since you've set raza to 0 before.
Here's how a sphere class could look like:
public class Sphere {
private final double radius;
public Sphere(double radius) {
this.radius = radius;
}
public double getArea() {
return 4 * Math.PI * this.radius * this.radius;
}
public double getVolume() {
return (4.0 / 3) * Math.PI * this.radius * this.radius * this.radius;
}
}
Key points:
its fields are final: they can't change.
there is no need to store the volume and the area as fields, since they are derived from the radius
getters don't try to modify the object. They just compute a value and return it.
You are using the same point (p1) to calculate raza, thus replacing the value you used in the constructor. And then you used raza to calculate the other values in the Sfera class.
In the Cub class you are doing the same, so the programm is doing what it is supposed to do. If you calculate those things between the point and itself it will give you 0.
As a result the values you used in your constructor where overwritten by your methods.
System.out.println("Raza sfera:" + obSfera.getRaza(p1,p1));
Sorry, I can't translate what is Raza, but this method calculates distance between two points.
You pass into getRaza the same point. Distance between two identical points is zero. That is why getRaza returns zero.
You assign distance between points to internal field Sfera::raza inthe method getRaza
public double getRaza(Punct p1,Punct p2)
{
raza=Math.sqrt(Math.pow(p2.x-p1.x,2)+Math.pow(p2.y-p1.y, 2)+Math.pow(p2.z-p1.z, 2));
return raza;
}
So after calling obSfera.getRaza(p1,p1) the field obSfera.raza equals to zero.
All other methods use obSfera.raza in their formulas:
public double getAria()
{
aria=4*Math.PI*raza*raza;
return aria;
}
public double getVolumul()
{
volumul=4/3*Math.PI*raza*raza*raza;
return volumul;
}
Put raza value into your formulas:
volumul = 4/3*Math.PI*raza*raza*raza = 4/3*Math.PI*0*0*0 = 0
aria = 4*Math.PI*raza*raza = aria=4*Math.PI*0*0
The same is happening with the object obCub
create another object for class Punct and rewrite the code like below:
public class TestTema
{
public static void main(String[] args_)
{
Punct p1=new Punct(2, 2, 2) {};
Punct p2=new Punct(3, 3, 3) {};
Sfera obSfera=new Sfera(1,2,3,1,1,1,1);
System.out.println("Raza sfera:" + obSfera.getRaza(p1,p2));
System.out.println("Aria sfera=" + obSfera.getAria());
System.out.println("Volum sfera= " +obSfera.getVolumul());
// System.out.println("Centrul= "+obSfera.getSuprafata());
Cub obCub=new Cub(1,2,3,1,1,1,1);
System.out.println("Lungime latura cub:"+obCub.getLatura(p1,p2));
System.out.println("Aria cubului="+obCub.getAria());
System.out.println("Volumul cubului="+obCub.getVolumul());
// System.out.println("Suprafata="+obCub.getCentrul());
}
}
classes Cub and Sfera both refering the same object p1, so the distance value Math.pow(p2.x-p1.x,2) always be 0.
I am trying to produce a proceduraly generated 2D map, but i am stuck on creating the accsessor method to just return what type a specific location is.
I created a custom square class that has the variable type and special..
here is the square class
public class Square{//custom object for map class
private int type = 0;
private boolean special = false;
public int getType(){//returns type of square
return type;
}
public boolean isSpecial(){//returns boolean for whether square is special or not
return special;
}
public void setType(int a){//sets type for square if input is between 1 and 5
if(a>=1&&a<=5){
type = a;
}
}
public void setSpecial(){//sets special status to true
special = true;
}
}
I've tested the square class to make sure it works, I am getting trouble in my Map class when i try to create a method that returns the type of square at a given coordinates
here is the applicable code from that class
public class Map{
private int mapWidth;
private int mapHeight;
Square newMap[][] = new Square[0][0];
public Map(int width, int height){//constructor sets map height and width and instantiates a 2d array with the arguments
if(width <= 0){//if user inputs numbers less than 1 will set according attribute to 1
width = 1;
}
if (height <= 0){
height = 1;
}
mapWidth = width;
mapHeight = height;
Square newMap[][] = new Square[mapWidth][mapHeight];
}
public void create(){
}
public int getWidth(){//accssesor methods
return mapWidth;
}
public int getHeight(){
return mapHeight;
}
public int getType(int x, int y){
return newMap[y][x].getType();
}
}
I know that i am probably doing something horribly wrong but any help will be greatly appreciated.
I am trying to return a Point from a circle.java class that extends a shape class. i keep getting a null pointer exception at the moment. i need to retrun the center point using the inherited getPoints(); method but the inhereted method returns a array and value to be returned from circle is not an array. how would i return the center point without makeing a seperate return method.
my Shape class is as follows
import java.awt.Point;
public abstract class Shape {
private String name;
private Point[] points;
protected Shape(){};
protected Shape(String aName) {
name = aName;
}
public final String getName() {
// TODO Implement method
return name;
}
protected final void setPoints(Point[] thePoints) {
points = thePoints;
}
public final Point[] getPoints() {
// TODO Implement method
return points;
}
public abstract double getPerimeter();
public static double getDistance(Point one, Point two) {
double x = one.getX();
double y = one.getY();
double x2 = two.getX();
double y2 = two.getY();
double x3 = x - x2;
double y3 = y - y2;
double ypow = Math.pow(y3, 2);
double xpow = Math.pow(x3, 2);
double added = xpow + ypow;
double distance = Math.sqrt(added);
return distance;
}
}
my circle class is a follows
import java.awt.Point;
public class Circle extends Shape{
private double radius;
public Circle(Point center, int aradius) {
super("Circle");
radius = aradius;
if(radius < 0){
radius = 0;
}
else{
radius = aradius;
}
}
#Override
public double getPerimeter() {
double perim = 2 * Math.PI * radius;
return perim;
}
public double getRadius(){
return radius;
}
}
The simplest solution I can think of is simply to use the setPoints method from the Shape class...
public Circle(Point center, int aradius) {
super("Circle");
//...
setPoints(new Point[]{center});
}
The reason you're getting a NullPointerException is because you never setPoints of Shape.
I'm not sure what points is supposed to contain but the only thing that would kind of make sense to me is all the points within the shape. Which IMO gets a bit tricky to determine with shapes like circles and determining a center point seems even trickier (although I guess for a circle it would pretty much be the middle point of the array depending on the order?).
(On second thought points could also contain whatever the subclass decides it should, like 1 center point for a circle and 4 points for a rectangle..)
Anyway you will have to fill the points array of Shape (by calling setPoints) with some data before you can use getPoints.
I am writing some code in processing to display a random walker using the Monte Carlo algorithm.
Now I have specified a walker class with inside two important methods a step function which controls the movement and a stepsize function which controls the speed and direction.
But for some reason I cannot properly call the stepsize method in the step method. As a result,the program draws nothing on the screen. The code executes, I have no errors.
My code:
import java.util.*;
class Walker {
float y;
float x;
float monte_carlo;
Walker() {
x = width/2;
y= height/2;
}
void display(){
stroke(0);
point(x,y);
}
float stepsize (float r1) {
while (true) {
r1 = random(0,10);
float probability = r1;
float r2 = random(0,10);
if (r2 < probability) {
return r1;
}
}
}
void step() {
x += stepsize(monte_carlo);
y += stepsize(monte_carlo);
}
}
Walker w;
void setup() {
size(400,400);
w = new Walker();
background(255);
}
void draw() {
w.display();
w.step();
}
This problem has been bothering me for a while and I would really appreciate it if someone could enlighten me!
Java is pass-by-value, so your stepsize() method will not modify your monte_carlo variable. Just use the variable directly in the method instead of passing it in.
float stepsize () {
while (true) {
monte_carlo = random(0,10);
float probability = monte_carlo;
float r2 = random(0,10);
if (r2 < probability) {
return monte_carlo;
}
}
}
You are always calling stepsize(0.0f) whenever stepsize(monte_carlo) is called, because float monte_carlo; means the variable is initialized with its default value (which is 0.0f) and you never modify it in your code.
Also, since you never use the value passed to the stepsize() function, you should use this signature instead :float stepsize().