What's wrong with my progam?
public class Square{
public int x;
public Square() {
int x[] = new int[10];
int y;
x[0] = 7;
}
public void root() {
for (int i = 0; i < 10; i++) {
x[i+1] = x[i] - (Math.pow(x[i] - 2.5, 2)) / (2 * (x[i] - 2.5));
System.out.println(x[i + 1]);
}
}
}
I don't get what's wrong, my for loop does not seem to be working and it keeps on displaying the error for some reason. Could someone help me figure this out?
Okay, I wrote this program now:
public class Square
{
public double x[];
public void root()
{
double x[] = new double[10];
x[0]=7;
for(int i=0; i<8; i++)
{
x[i+1]=x[i]-(Math.pow(x[i]-2.5,2))/(2*(x[i]-2.5));
System.out.println(x[i+1]);
}
}
}
And it is showing this output:
3.625
3.0625
2.78125
2.640625
2.5703125
2.53515625
2.517578125
java.lang.NullPointerException
at Square.root(Square.java:14)
java.lang.ArrayIndexOutOfBoundsException: Index 10 out of bounds for length 10 at Square.root(Square.java:11)
I don't know why I'm getting these errors. Also, the answer should be 6.25 at some point. But, it doesn't show that output.
Your constructor has a local variable int[] x which is disarded at the end of the constructor.
Try this:
public class Square{
// initialize to array of ten ints
public int x[] = new int[10];
public Square() {
x[0] = 7;
}
public void root() {
for (int i = 0; i < 10; i++) {
x[i+1] = x[i] - (Math.pow(x[i] - 2.5, 2)) / (2 * (x[i] - 2.5));
System.out.println(x[i + 1]);
}
}
}
Edit: The int y is local to the constructor, it is discarded at the end of the constructor scope, too.
This is because you have defined x previously as just an int, instead of an array of ints.
Try this:
public class Square {
public int x[];
public Square() {
this.x = new int[10];
int y;
x[0] = 7;
}
public void root() {
for(int i = 0; i < 10; i++) {
x[i + 1] = x[i] - (Math.pow(x[i] - 2.5, 2)) / (2 * (x[i] -2.5));
System.out.println(x[i + 1]);
}
}
}
Here is the commented code explaining the problem :
public class Square
{
// Here, x is defined as an attribute of class Square, of type int
public int x;
public Square()
{
// Here, x is locally defined as a local variable, of type int[]
// It shadows the attribute x. This is considered as a bad practice.
int x[] = new int[10];
int y;
// Here, x is the local variable, of type int[]. It IS an array so
// this line is valid.
x[0]=7;
}// From this point, the local variable x is not defined anymore
// (that is the point of a local variable)
Now here :
public void root()
{
for(int i=0; i<10; i++)
{
// Here, x is referencing the attribute of class Square, which is an int
// But you try to access it as if it was and int[]
x[i+1]
First you must declare x as an array:
public int[] x;
notice that the java style is not int x[];
Then inside Square() you have to initialize x like this:
x = new int[10];
Finally, this:
(Math.pow(x[i] - 2.5, 2)) / (2 * (x[i] - 2.5))
returns a double so you have to cast it to int:
x[i+1] = x[i] - (int) ((Math.pow(x[i] - 2.5, 2)) / (2 * (x[i] - 2.5)));
So your code should be:
public int[] x;
public void Square() {
x = new int[10];
x[0] = 7;
}
public void root() {
if (x == null)
Square();
for(int i = 0; i < x.length - 1; i++) {
x[i+1] = x[i] - (int) ((Math.pow(x[i] - 2.5, 2)) / (2 * (x[i] - 2.5)));
System.out.println(x[i+1]);
}
}
Inside the loop you are accessing the i + 1 item so the counter of the loop must take values up to x.length - 2, this is why I have in the code: i < x.length - 1.
I have removed the declaration of y from Square() as it is not used.
public class Square
{
public double x[];
public Square()
{
this.x = new double[10];
x[0]=7;
}
public void root()
{
System.out.println(x[0]);
for(int i=1; i<10; i++)
{
x[i]=x[i-1]-(Math.pow(x[i-1]-2.5,2))/(2*(x[i-1]-2.5));
System.out.println(x[i]);
}
}
}
Try use this code
public class Square
{
public double x[];
public void root()
{
x = new double[10];
x[0]=7;
for(int i=1; i<10; i++)
{
x[i]=x[i-1]-(Math.pow(x[i-1]-2.5,2))/(2*(x[i-1]-2.5));
System.out.println(x[i]);
}
}
}
Related
The idea is each iteration will move the [x] every time it prints. However it obviously can't print a 0x0 matrix. As you can see I summoned the constructor in the program to have the variables 4, 4. Yet for some reason, after running it, the program still outputs 0,0.
public class MovingX{
private int rowsN;
private int columnsM;
private int[][] matrixArr = new int[rowsN][columnsM];
private int x = 0;
private int y = 0;
public MovingX(int n, int m){
n = rowsN;
m = columnsM;
}
public void forLoopGrid(){
for(int i = 0; i < matrixArr.length; i++){
for(int j = 0; j < matrixArr.length; j++){
if(i == x && j == y) System.out.print("[x] ");
else System.out.print("[ ] ");
}
System.out.println();
}
System.out.println();
}
public void moveX(){
if(x < rowsN) x++;
else{
x = 0; y++;
}
}
public void runProgram(){
System.out.println("Program Starting");
System.out.println("Rows, Columns: " + rowsN + " " + columnsM);
for(int i = 0; i < (rowsN * columnsM); i++){
System.out.println("Stuff happening");
forLoopGrid();
moveX();
}
System.out.println("Program Ending");
}
public static void main(String[] args){
MovingX xLoop = new MovingX(4, 4);
xLoop.runProgram();
}
}
The problem seems to be the fact that you are assigning your object's fields(rowsN,columnsM) to the arguments(n,m) supplied to your class constructor.
You see, it doesn't matter what arguments you supply during instantiation when you use those local constructor variables to store the default value of your object's fields. You get (0,0) because all object fields get initialized to a default value and for int, that happens to be 0.
This should work--
public MovingX(int n, int m){
rowsN=n; //n = rowsN;
columnsM=m; //m = columnsM;
}
Reason maybe with the assignment.
public MovingX(int n, int m){
rowsN = n;
columnsM = m;
}
Try this, they may work.
I need to fill a 2D Array with numbers between 2 and 6, given by the user (is just part of a bigger proyect) but when I give the number I only get another request for a number.
public static int[][] crearTablero(int tamaño)
{
int[][] tablero = new int[tamaño][tamaño];
return tablero;
}
public static void imprimeTablero(int[][] tablero)
{
for(int i = 0; i<tablero.length; i++)
{
for(int j = 0; j<tablero[i].length; j++)
{
System.out.print(tablero[i][j] + " ");
}
System.out.println();
}
}
public static void swap(int[][] tablero, int x1, int y1, int x2, int y2)
{
int temp = tablero[x1][y1];
tablero[x1][y1] = tablero[x2][y2];
tablero[x2][y2] = temp;
}
public static void rellenarTablero(int[][] tablero) {
for (int x = 0; x < tablero.length; x++) {
for (int y = 0; y < tablero[x].length; y++) {
tablero[x][y] = aleatorio(numeroColores());
}
}
}
public static void shuffleBoard(int[][] tablero)
{
Random rnd = new Random();
int randX = 0;
for(int x = 0; x<tablero.length; x++)
{
randX = rnd.nextInt(tablero.length);
int[] temp = tablero[x];
tablero[x] = tablero[randX];
tablero[randX] = temp;
}
}
public static int numeroColores(){
int colores = 0;
System.out.print("Numero de colores (entre 2 y 6): ");
Scanner scn = new Scanner(System.in);
colores = scn.nextInt();
while(colores < 2 || colores > 6)
{
System.out.println("Invalid matrix size. Re-enter ");
}
return colores;
}
public static int aleatorio(int colores) {
int l = (int) (Math.floor(Math.random()*(colores-2)) + 2);
return l;
}
I would really appreciate some help because I don't know how to continue, Thanks.
You call numeroColores() in a for-loop in a for-loop, so you are of course asked multiple times for it.
Btw. you have an endless loop if you type in 1 or smaller or 7 or bigger with constantly getting the same line printed out and not asking for new input
Try this code to generate the random value between 2 and 6
public static int aleatorio(int colores) {
int l = 0;
while(l < 2 || l > 6) {
l = (int) (Math.floor(Math.random()*(colores-2)) + 2);
}
return l;
}
I'm trying to create two classes, one to define a point and another for array operations. I'm trying to create a method to sort an array of coordinates in ascending order based on y coordinates. I've tried following examples, but I keep running into a runtime error where the array is only partially sorted.
public class Point
{
private double x;
private double y;
public Point(double x_coord, double y_coord)
{
x = x_coord;
y = y_coord;
}
public boolean lessThan(Point anotherPoint)
{
if(y < anotherPoint.y)
{
if(x < anotherPoint.x)
{
return true;
}
}
return false;
}
}
public class PointArray
{
private Point[] points = new Point[count];
public PointArray(double[] doubleArray)
{
if(doubleArray.length % 2 == 0)
{
for(int i = 0, j = 0; i < 3; i++, j += 2)
{
double x = doubleArray[j];
double y = doubleArray[j + 1];
points[i] = new Point(x, y);
}
}
else
{
System.out.println("Error: The given array must be even.");
System.exit(0);
}
}
public void sort()
{
double x = 0;
double y = 0;
Point newPoint = new Point(x, y);
Point temp = new Point(x, y);
for (int i = 0; i < points.length - 1; i++)
{
for(int j = i + 1; j < points.length; j++)
{
int minIndex = i;
if(points[minIndex].lessThan(points[j]) == false)
{
temp = points[minIndex];
points[minIndex] = points[j];
points[j] = temp;
}
}
}
}
This code causes the array {5.6, 7.1, 4.9, 13.17, 9.3, 2.9} to first be stored as ordered pairs {(5.6, 7.1), (4.9, 13.17), (9.3, 2.9)}. but it does not sort them properly. After the first and third points are swapped, the second and third are not, even though the y coordinate of the third is smaller.
[(9.3, 2.9), (4.9, 13.17), (5.6, 7.1)]
EDIT: Another issue appeared related to the same assignment. This method is supposed to take two PointArray objects and compare them for equality by the x and y components. My idea was to sort both arrays and then compare the components using a method in the Point class, but I'm not sure how to define each PointArray in terms of an (x, y) point.
public boolean equals(Point anotherPoint)
{
if(x == anotherPoint.x && y == anotherPoint.y)
{
return true;
}
return false;
}
public boolean equals(PointArray anotherPointArray)
{
double x = 0;
double y = 0;
double xAnother = 0;
double yAnother = 0;
Point newPoint = new Point(x, y);
Point newAnotherPoint = new Point(xAnother, yAnother);
anotherPointArray.sort();
for(int i = 0; i < points.length; i++)
{
for(int j = 0; i < points.length; j++)
{
if(newPoint.equals(newAnotherPoint))
{
return true;
}
}
}
return false;
}
Your current lessThan method will give true only if both x and y are smaller. To sort by y alone use
public boolean lessThan(Point anotherPoint)
{
return y < anotherPoint.y;
}
I'm trying to fill a matrix with stars (*) to draw Bresenham's line, but when i'm printing out the thing the matrix is only filled with one star i don't know whats wrong. Language is Java
public class PtLine extends VectorObject{ // inherites from another class
private int bx;
private int by;
private int delX;
private int delY;
public PtLine(int id,int x,int y,int bx,int by){
super(id,x,y);
this.bx = bx;
this.by = by;
this.delX = this.bx-x;
this.delY = this.by-y;
}
public void draw ( char [][] matrix ){ // filling the martic with stars
int D = 2*delY - delX;
matrix[x][y] = '*';
int j = y;
for (int i=x+1;i==bx;i++){
if(D > 0){
j+=1;
matrix[i][j]='*';
D = D + (2*delY-2*delX);
}
else{
matrix[i][j]='*';
D = D + (2*delY);
}
}
}
}
The following code is when i'm trying to print out the matrix
class Question3{
public static void main ( String args [] ){
char[][] matrix = new char[20][20];
for (int y = 0; y < 20; y++) {
for (int x = 0; x < 20; x++) {
matrix[y][x] = ' ';
}
}
PtLine n = new PtLine(6,6,6,13,13);
n.draw(matrix);
for (int y = 0; y < 20; y++) {
for (int x = 0; x < 20; x++) {
System.out.print(matrix[x][y]);
}
System.out.println();
}
}
}
It's likely that you have to change i==bx with i!=bx:
public void draw ( char [][] matrix ){ // filling the martic with stars
int D = 2*delY - delX;
matrix[x][y] = '*';
int j = y;
for (int i=x+1;i!=bx;i++){ // here
...
}
}
The for loop continues while this condition is true. In your code loop finishes immediately at start, before the first iteration, because this condition is false.
I am creating java project which takes in two arrays and calculates a linear regression.
I have 4 classes, one that is a constructor (RegressionModel), one that does the math equations (Math1) and contains all the formulas, a computational class (FinalLinearRegressionModel) which extends the constructor class which I initialize a super constructor and use the values to make methods which call my Math class. Finally I have my tester class which calls the FinalLinearRegressionModel and does the computations from there.
Is this the right way to go about this or should I just put the methods I have inside the FinalLinearRegressionModel into my RegressionModel, and I would therefore have no need to extend my constructor because I am not adding any instance variables into my constructor? Here are my classes:
public class RegressionModel {
public static final double[] DEFAULT_X = new double[0];
public static final double[] DEFAULT_Y = new double[0];
public static final boolean DEFAULT_ISCALCULATED = false;
public double [] xValues;
public double [] yValues;
public boolean isCalculated;
public RegressionModel()
{
xValues = DEFAULT_X;
yValues = DEFAULT_Y;
isCalculated = DEFAULT_ISCALCULATED;
}
public RegressionModel(double[] x, double[] y)
{
if(x == null || y == null)
{
System.out.println("Fatal Error creating regression model.");
System.exit(0);
}
else if(x.length == 0 || y.length == 0)
{
System.out.println("Fatal Error one or more zero lengths.");
System.exit(0);
}
else if(x.length != y.length)
{
System.out.println("Fatal Error array lengths are not equal.");
}
else
{
xValues = x;
yValues = y;
isCalculated = false;
}
}
public double[] getXValues()
{
return this.xValues;
}
public double[] getYValues()
{
return this.yValues;
}
}
public class Math1 extends RegressionModel {
public static double covariance(double[] x, double[] y)
{
double meanX;
double meanY;
double covariance;
meanX = mean(x);
meanY = mean(y);
covariance = 0;
for(int index = 0; index < x.length; index++)
{
covariance += (x[index] - meanX) * (y[index] - meanY);
}
covariance /= (x.length -1);
return covariance;
}
public static double mean(double[] values)
{
double sum;
sum = 0.0;
for(int index = 0; index < values.length; index++)
{
sum += values[index];
}
return sum / values.length;
}
public static double xxBar(double[] x)
{
double xxbar;
xxbar = 0.0;
for(int index = 0; index < x.length; index++)
{
xxbar += (x[index] - mean(x)) * (x[index] - mean(x));
}
return xxbar;
}
public static double yyBar(double[] y)
{
double yybar;
yybar = 0.0;
for(int index = 0; index < y.length; index++)
{
yybar += ((y[index] - mean(y)) * (y[index] = mean(y)));
}
return yybar;
}
public static double xyBar(double[] x, double[] y)
{
double xybar;
xybar = 0.0;
for(int index = 0; index < x.length; index++)
{
xybar += ((x[index] - mean(x)) * (y[index] - mean(y)));
}
return xybar;
}
public static double beta1(double[] x, double[] y)
{
return xyBar(x,y)/xxBar(x);
}
public static double beta0(double[] x, double[] y)
{
return mean(y) - beta1(x,y) * mean(x);
}
public static double sumOfSquaresDueToRegression(double[] y)
{
double meanY;
meanY = mean(y);
double sumOfSquaredDeviations = 0.0;
for(int index = 0; index < y.length; index++)
{
sumOfSquaredDeviations += (Math.pow(y[index] - meanY, 2));
}
return sumOfSquaredDeviations;
}
public static double sumOfSquaresTotal(double[] y)
{
double sumOfSquaresTotal;
sumOfSquaresTotal = 0.0;
for(int index = 0; index < y.length; index++)
{
sumOfSquaresTotal += (Math.pow(y[index] - mean(y), 2));
}
return sumOfSquaresTotal;
}
public static double degreesOfFreedom(double[] x)
{
return x.length - 2;
}
public static double fit(double[] x, double[] y)
{
double fit;
fit = 0.0;
for(int index = 0; index < x.length; index++)
{
fit = beta1(x,y) * x[index] + beta0(x,y);
}
return fit;
}
public static double r2(double[] y)
{
return sumOfSquaresDueToRegression(y) / yyBar(y);
}
public static double sumOfSquaresDueToError(double[] x, double[] y)
{
double sumOfSquaresError;
sumOfSquaresError = 0.0;
for(int index = 0; index < y.length; index++)
{
sumOfSquaresError += (Math.pow(y[index] - beta1(x,y), 2));
}
return sumOfSquaresError;
}
}
public class FinalLinearRegressionModel extends RegressionModel{
public double b0;
public FinalLinearRegressionModel(double[] x, double[] y)
{
super(x,y);
}
public double computeb0()
{
return b0 = Math1.beta0(xValues,yValues);
}
}
public class Test {
public static void main(String args[])
{
double[] x = {2, 3, 4, 5, 6, 8, 10, 11};
double[] y = {21.05, 23.51, 24.23, 27.71, 30.86, 45.85, 52.12, 55.98};
FinalLinearRegressionModel regression1;
regression1 = new FinalLinearRegressionModel(x,y);
System.out.println(regression1.computeb0());
}
}
Move your computeb0() method up into RegressionModel and get rid of FinalLinearRegressionModel.
Also why does Math1 extend RegressionModel? All the methods are static so it doesn't use any of the instance fields of RegressionModel.
Next, computeb0 method's return looks weird:
return b0 = Math1.beta0(xValues,yValues);
is returning the result of the assignment which I think happens to be the correct answer but that is not a common idiom in java programming and will confuse others who read your code.
b0 = Math1.beta0(xValues,yValues);
return b0;
would what you want
Even better would be not to save b0 to an instance value at all. There's no need
return Math1.beta0(xValues,yValues);
Finally, as mentioned by Commenter Chief Two Pencils, calling System.exit() in a constructor is bad form. You should throw an exception instead:
//don't need else keyword in this case
if(x == null || y == null)
{
throw new NullPointerException("x and y can not be null");
}
if(x.length == 0 || y.length == 0)
{
throw new IllegalArgumentException("one or more zero lengths.");
}
if(x.length != y.length)
{
throw new IllegalArgumentException("array lengths are not equal.");
}
RegressionModel represent your vertices. They could have been stored as an array of Vertice, but you choose a separate double [] for x and y which is also fine.
However my advice is because your model is quite simple, not to introduce any new 'Uber' model for your array or list. Just let it be what it is. Either a List or an array. Maybe even better: do implement your Vertice as an actual Vertice class, so you can represent your model as either List<Vertice> or Vertice []. You can add static helper methods in Vertice to create your List or array out of your double [] arrays.
import java.util.Arrays;
import java.util.List;
public class Vertice {
final public double x;
final public double y;
public Vertice(double x,double y) {
this.x = x;
this.y = y;
}
static public Vertice [] arrayFrom(double [] xs,double [] ys) {
// Allow to below automatically throw a NullPointerException without explicitly checking
if (xs.length != ys.length) throw new IllegalArgumentException("Arrays of diferent size: "+xs.length+" != "+ys.length);
Vertice [] vs = new Vertice[xs.length];
for (int i=0;i<xs.length;i++) vs[i] = new Vertice(xs[i],ys[i]);
return vs;
}
static public List listFrom(double [] xs,double [] ys) {
return Arrays.asList(arrayFrom(xs,ys));
}
}
So gone is RegressionModel. As explained by #dkatzel, there is also no need to extend the model into Math1, as it contains only calculations. And actual maybe 'model' here could mean your mathematical model, so as your RegressionModel is not used anymore to represent your vertices, you can now directly rename Math into RegressionModel.
At first glance - with earlier suggestions - it looks nice and clean, but likely you will run into issues that will require a less elegant solution. Example an avg(double[]) now needs to be separately an avgX(List<Vertice>) and avgY(List<Vertice>).
But hey, now enter the world of Stream and parallel processing. Maybe you can refactor everything to take advantage of Java 8:
import java.util.List;
public class RegressionApp {
public static void main(String args[])
{
double[] x = {2, 3, 4, 5, 6, 8, 10, 11};
double[] y = {21.05, 23.51, 24.23, 27.71, 30.86, 45.85, 52.12, 55.98};
List<Vertice> v = Vertice.listFrom(x, y);
RegressionModel regression1 = v.stream().parallel()
.collect(RegressionModel.summarize());;
System.out.println(regression1.b0);
}
}
Would that not be something?
That would be probably a lot of work implementing - but I just couldn't let it go without mention.