"new way for loop" in Java, not working, suggestion? - java

this is my problem:
I was trying to use the new for loop in java to print out some strings with doubles. When i compile the code, no errors, but no output, it's like if the for loop isn't working, any help?
the loop it's right in the end, i've printed all the code just to be sure.
abstract class Figure3D {
private float[] center;
protected void setCenter(float[] center){this.center = center;}
public abstract double calcolateVolumn();
protected abstract String figureType();
public void printVolumn(){
System.out.println("Volumn "+ figureType() + calcolateVolumn());
}
}
class Cube extends Figure3D{
private float side;
public Cube(float side, float[] center){
this.side = side;
setCenter(center);
}
#Override
protected String figureType(){
return "Cube ";
}
#Override
public double calcolateVolumn(){
return side*side*side;
}
}
class Sphere extends Figure3D {
private float radius;
public Sphere(float radius, float[] center){
this.radius = radius;
setCenter(center);
}
protected String figureType(){return "Sphere ";}
public double calcolateVolumn(){return ((4f/3f)*radius*radius*radius*3.14f);}
}
import java.util.ArrayList;
import java.util.List;
class TridimensionalFigures {
public static void main(String[] args) {
List<Figure3D> figures3d = new ArrayList<>(10);
Sphere sphere;
Cube cube;
for (int i = 0; i < figures3d.size(); i++) {
sphere = new Sphere(i, new float[] {i, i, i});
figures3d.add(i, sphere);
i++;
cube = new Cube(i, new float[] {i, i, i});
}
//TOFIX: it needs to print out the volums of all the objects in the arraylist
for (Figure3D figures : figures3d) {
System.out.printf("The volumns is: %s %n", figures.calcolateVolumn());
}
}
}

figures3d.size() is 0, so you are not adding anything to the list.
Try changing
for (int i = 0; i < figures3d.size(); i++) {
to
for (int i = 0; i < 10; i++) {

The problem is, the list is never actually populated.
You set it's initial capacity using the constructor, but that doesn't change the size; it just prevents reallocations later.
Because the size is 0, the populizing loop never runs, so the second loop (in question) is skipped due to the list being empty.
Instead of using the list's size to control the populating loop, extract the magic 10 into its own variable, and loop while i < tenVariable.

Related

Trying to sort array using the interface comparable in JAVA

I have an abstract class and and few subclasses, and a main class
I am have array of shapes and trying to sort the array in descending order of area using comparable
I have a code so far for comparable but it would not sort and would not print .
SHAPE ABSTRACT CLASS
import java.text.*;
public abstract class shape implements Comparable<shape> {
private int id;
private String label;
private static int counter = 1; // to keep count and unique over all classes
private static DecimalFormat df2 = new DecimalFormat("#.##");
public shape(String label) {
this.id = counter;
counter ++ ; //this is counter for unique id can also have a default constructor seperate for count
this.label = label;
}
public int getId() {
return id;
}
public String getLabel() {
return label;
}
public interface Comparable {
public int compareTo(shape o);
}
public int compareTo(shape o) {
if (this.CalcArea() > o.CalcArea())
return 1;
else if (this.CalcArea() < o.CalcArea())
return -1;
else
return 0;
}
//to calculate area= abstract method
public abstract double CalcArea(); // this is the prototype and has to be used once in derived classes
public String toString() {
//df2.format(CalcArea())
return "ID " + this.id + ": the shape is " + label + " and the area calculated is "+
df2.format(CalcArea());
}
}
// DRIVER MAIN CLASS
import java.util.*;
public class DrawingApp {
/*public DrawingApp() {
}*/
public static void main(String[] args) {
int shapeType;
int i; //two for loops so better here
//next gaussian if using double
shape[] shaper = new shape[10]; //instantiating array object not the shape
Random num = new Random();
Random num1 = new Random(); //*100 + 1
for ( i = 0; i < 10 ; i++) {
shapeType = num.nextInt()% 2 ;
if(shapeType == 0 ) {
shaper[i] = new circle((num1.nextDouble()*9)+1); //can use random as the shapes are created randomly and array of ten
}else if(shapeType == 1) {
shaper[i] = new Rectangle((num1.nextDouble()*9)+1,(num1.nextDouble()*9)+1);
}else {
shaper[i] = new Triangle((num1.nextDouble()*9)+1,(num1.nextDouble()*9)+1);
}
}
for ( i = 0; i < 10 ; i ++) {
shaper[i].CalcArea();
}
for(shape s : shaper){
System.out.println(s);
}
}
}
Considering that your Circle, Rectangle and Triangle classes are correctly implemented, add the line Arrays.sort(shaper); to sort the array. It will use your Shape's compareTo method to sort the shapes by area. As is, I do not see any attempt at sorting.
The for-loop where you call CalcArea() method also seems to do nothing, since you never use the return values.

Accessing objects from another class in java?

i know that this question has been asked many types, but i am not getting trough the problem. So following. I have created a class that is creating array of 2 positions. The goal is to create point coordinates so i can generate several points later. Hier is my code
import java.util.Random;
public class Coor {
private static int[] coord;
public static int[] generate(){
coord = new int[2];
return coord;
}
public static void printX(){
System.out.println("X = " + coord[0] );
}
public static void printY(){
System.out.println("Y = " + coord[1] );
}
public static int randomFill(){
Random rand = new Random();
int randomNum = rand.nextInt(99);
return randomNum;
}
public static void main(String args[]) {
generate();
for(int i = 0; i < 2; i++){
coord[i] = randomFill();
}
printX();
printY();
}
}
So, this is working perfect, but what I want is to create the points in another class and to use them there, but I have no idea how to achieve this. I am new to java, and I have almost understood some examples in the oracle docs, but can not implement it. Can you please help me a little? I just need one example class which is obtaining the coordinates of the points, after that I can extend it alone for my needs.
You should not make your data static and you should provide a public constructor see below.
public class Coord {
private int[] coord;
public Coord(int x, int y) {
coord = new int[2];
coord[0] = x;
coord[1] = y;
}
public void printX(){
System.out.println("X = " + coord[0] );
}
public void printY(){
System.out.println("Y = " + coord[1] );
}
public static void main(String[] args) {
Coord c1 = new Coord(10, 11);
Coord c2 = new Coord(23, 14);
}
}

Java Thread execution on same data

first of all here is the code, you can just copy an paste
import java.util.ArrayList;
public class RepetionCounter implements Runnable{
private int x;
private int y;
private int[][] matrix;
private int xCounter;
private int yCounter;
private ArrayList<Thread> threadArray;
private int rowIndex;
private boolean[] countCompleted;
public RepetionCounter(int x, int y, int [][]matrix)
{
this.x = x;
this.y = y;
this.matrix = matrix;
this.threadArray = new ArrayList<Thread>(matrix.length);
this.rowIndex = 0;
for(int i = 0; i < matrix.length; i++){
threadArray.add(new Thread(this));
}
countCompleted = new boolean[matrix.length];
}
public void start(){
for (int i = 0; i < threadArray.size(); i++){
threadArray.get(i).start();
this.rowIndex++;
}
}
public void count(int rowIndex)
{
for(int i = 0; i < matrix[rowIndex].length; i++){
if (matrix[rowIndex][i] == x){
this.xCounter++;
} else if (matrix[rowIndex][i] == y){
this.yCounter++;
}
}
}
#Override
public void run() {
count(this.rowIndex);
countCompleted[this.rowIndex] = true;
}
public int getxCounter() {
return xCounter;
}
public void setxCounter(int xCounter) {
this.xCounter = xCounter;
}
public int getyCounter() {
return yCounter;
}
public void setyCounter(int yCounter) {
this.yCounter = yCounter;
}
public boolean[] getCountCompleted() {
return countCompleted;
}
public void setCountCompleted(boolean[] countCompleted) {
this.countCompleted = countCompleted;
}
public static void main(String args[]){
int[][] matrix = {{0,2,1}, {2,3,4}, {3,2,0}};
RepetionCounter rc = new RepetionCounter(0, 2, matrix);
rc.start();
boolean ready = false;
while(!ready){
for(int i = 0; i < matrix.length; i++){
if (rc.getCountCompleted()[i]){
ready = true;
} else {
ready = false;
}
}
}
if (rc.getxCounter() > rc.getyCounter()){
System.out.println("Thre are more x than y");
} else {System.out.println("There are:"+rc.getxCounter()+" x and:"+rc.getyCounter()+" y");
}
}
}
What I want this code to do: I give to the object a matrix and tow numbers, and I want to know how much times these two numbers occurs in the matrix. I create as many thread as the number of rows of the matrix (that' why there is that ArrayList), so in this object I have k threads (supposing k is the number of rows), each of them count the occurrences of the two numbers.
The problem is: if I run it for the first time everything work, but if I try to execute it another time I get and IndexOutOfBoundException, or a bad count of the occurrences, the odd thing is that if I get the error, and modify the code, after that it will works again just for once.
Can you explain to me why is this happening?
You are using the same instance of RepetitionCounter for each thread:
for(int i = 0; i < matrix.length; i++){
threadArray.add(new Thread(this));
}
so they will all share the same rowIndex. The code is pretty confusing as it is, so I suggest you encapsulate the logic for the threads in a separate Runnable class with individual row ids:
class ThreadTask implements Runnable {
private int rowId;
private int[][] matrix;
public ThreadTask(int[][] matrix, int rowId) {
this.matrix = matrix; // only a reference is passed here so no worries
this.rowId = rowId;
}
public void run() {
// search on my row
}
}
then:
for(int i = 0; i < matrix.length; i++) {
threadArray.add(new Thread(new ThreadTask(matrix, i)));
}
You need to give each thread its own Runnable. Having them all share the same Runnable is going to cause disastrous race conditions. Separate out the logic each thread needs to do into a Runnable. Then move the part of the code that starts up the threads to a place outside the Runnable.
BTW look into Executors in the java.util.concurrent package, you don't have to use raw threads for this stuff. Also using Executors may give you a better idea about separating what goes into the Task from other stuff.

Collections.sort compile error - incompatible types

I have been developing an implementation of the neighbourhood algorithm in Java for a physics project I am working on. I'm brand new to Java so I apologize for any idiocy that results.
I have been getting the error
''
incompatible types
found : void
required: java.util.List<VoronoiPoint>
'' on line 22 from the Java compiler in attempting to compile the program shown below. I cannot figure out why the variable ''thelist'' somehow turns into a void when I declared it to be of type List<VoronoiPoint>. If anybody can explain to me what is going on it would be much appreciated!
import java.lang.Double;
import java.util.*;
public class VoronoiTiling
{
public static void main(String args[])
{
Integer n = 10; //Number of dimensions of model parameter space
Integer ns = 20; //Number of points per iteration
Integer nr = 4; //Number of cells to populate
Integer iterations = 5; //Number of iterations
List<VoronoiPoint> thelist = VoronoiList.startlist(ns,n);
//System.out.println(thelist);
//System.out.println(thelist.get(1).misfit);
for (Integer i=0 ; i<thelist.size() ; i++)
{
thelist.get(i).setmisfit();
}
List<VoronoiPoint> orderedlist = Collections.sort(thelist);
Double distance = EuclidianDistance((thelist.get(1)).location,(thelist.get(2)).location);
System.out.println(distance);
}
public static Double EuclidianDistance(Double[] point1, Double[] point2)
{
Double distance=0.0;
for (int i = 0; i < point1.length; i++)
{
distance = distance + Math.pow((point1[i]-point2[i]),2);
}
return Math.sqrt(distance);
}
}
The other classes I used are here:
The VoronoiList class:
import java.util.*;
public class VoronoiList
{
public static List<VoronoiPoint> startlist(Integer ns, Integer n)
{
List<VoronoiPoint> thestartlist = new ArrayList<VoronoiPoint>();
for (int i = 0; i < ns; i++)
{
thestartlist.add(new VoronoiPoint(0.,n));
}
return thestartlist;
}
}
The VoronoiPoint class:
import java.util.Random;
public class VoronoiPoint implements Comparable<VoronoiPoint>
{
Double[] location;
private Random generator = new Random();
Double misfit = -1.;
//***************************************************************
public VoronoiPoint(Double misfit, Integer n)
{
location = new Double[n];
ParameterBoundaries boundaries = new ParameterBoundaries(n);
for(int i = 0; i < n; i++)
{
location[i] = boundaries.getboundaries(2*i)+2*generator.nextDouble();
}
}
//***************************************************************
//public Double[] getlocation()
//{
//return location;
//}
public void setlocationi(Integer i, Double j)
{
location[i] = j;
}
//***************************************************************
public void setmisfit()
{
Integer n = location.length;
Double tempmisfit = 0.0;
for(Integer i = 0; i < n; i++)
{
tempmisfit = tempmisfit + Math.pow((location[i]),2);
}
misfit = Math.sqrt(tempmisfit); // Temporarily just distance to centre
}
//public Double getmisfit()
//{
//return misfit;
//}
public int compareTo(VoronoiPoint b)
{
if (this.misfit<b.misfit) return -1;
else if (this.misfit==b.misfit) return 0;
return 1;
}
}
And the parameter boundaries class:
public class ParameterBoundaries
{
private Double[] boundaries; /*Set to 2n where n is dimensions of parameter space,
* it just makes it easier*/
public ParameterBoundaries(Integer n)
{
boundaries = new Double[2*n];
for(Integer i = 0; i<n; i++)
{
boundaries[2*i] = -1.0;
boundaries[2*i+1] = 1.0;
}
}
public Double getboundaries(Integer i)
{
return boundaries[i];
}
}
Collections.sort(..) sorts the original list. It doesn't return a new list. (Its return type is void)
Your code is wrong. Collections.sort() is an in-place sort function; it modifies the given list argument and returns nothing (void).

Java how to sort an ArrayList of Point objects

I'm using the Point Class to manage a list of (x,y) coordinates and I need to sort them in order of X.
I read online to make a new class PointCompare that implements Comparator, however I'm not sure how this works and therefore I have a compiler error in the sortByXCoordinates method.
Help would be appreciated a lot, and any comments are welcome, thanks in advance.
Here is some of my code:
import javax.swing.JOptionPane;
import java.awt.Point;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
//import java.util.Iterator;
public class ConvexHullMain {
private Point coordinates = new Point(0, 0);
private final int MAX_POINTS = 3;
private ArrayList<Point> coordinateList = new ArrayList<Point>();
public void inputCoordinates() {
String tempString; // temp string for JOptionPane
int tempx = 0;
int tempy = 0;
for (int i = 0; i < MAX_POINTS; i++) {
try {
// input x coordinates
tempString = JOptionPane.showInputDialog(null,
"Enter X coordinate:");
tempx = Integer.parseInt(tempString);
// input y coordinates
tempString = JOptionPane.showInputDialog(null,
"Enter Y coordinate:");
tempy = Integer.parseInt(tempString);
coordinates.setLocation(tempx, tempy);// set input data into
// coordinates object
coordinateList.add(coordinates.getLocation()); // put in
// arrayList
} // end Try
catch (NumberFormatException e) {
System.err.println("ERROR!");
main(null);
} // end catch
}// end for loop
}
public void displayPoints() {
for (int i = 0; i < MAX_POINTS; i++) {
JOptionPane.showMessageDialog(null, "Point number " + (i + 1)
+ " is: " + coordinateList.get(i));
}
// alt method
// Iterator i = coordinateList.iterator();
// String outputTemp;
// while (i.hasNext()) {
// outputTemp = i.next().toString();
// JOptionPane.showMessageDialog(null, "Point number " + " is: "
// + outputTemp);
// }
}
/**
* This sorts the points by the X coordinates
*/
public void sortByXCoordinates(){
coordinateList.sort(coordinates, new PointCompare());
}
public class PointCompare implements Comparator<Point> {
public int compare(Point a, Point b) {
if (a.x < b.x) {
return -1;
} else if (a.x > b.x) {
return 1;
} else {
return 0;
}
}
}
public static void main(String[] args) {
ConvexHullMain main = new ConvexHullMain();
main.inputCoordinates();
main.displayPoints();
}
}
private ArrayList<Point> coordinateList = new ArrayList<Point>();
...
Collections.sort(coordinateList, new PointCompare());
...
public class PointCompare implements Comparator<Point> {
public int compare(Point a, Point b) {
if (a.x < b.x) {
return -1;
}
else if (a.x > b.x) {
return 1;
}
else {
return 0;
}
}
}
You were close. The problem you had was simply that you invoked
public void sortByXCoordinates(){
coordinateList.sort(coordinates, new PointCompare());
}
What you want is this:
import java.awt.Point;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import javax.swing.JOptionPane;
public class MainClass {
private final Point coordinates = new Point(0, 0);
private final int MAX_POINTS = 3;
private final ArrayList<Point> coordinateList = new ArrayList<Point>();
public void inputCoordinates() {
String tempString;
int tempx = 0;
int tempy = 0;
for (int i = 0; i < this.MAX_POINTS; i++) {
try {
tempString = JOptionPane.showInputDialog(null, "Enter X coordinate:");
tempx = Integer.parseInt(tempString);
tempString = JOptionPane.showInputDialog(null, "Enter Y coordinate:");
tempy = Integer.parseInt(tempString);
this.coordinates.setLocation(tempx, tempy);// set input data into
this.coordinateList.add(this.coordinates.getLocation()); // put in
}
catch (final NumberFormatException e) {
System.err.println("ERROR!");
main(null);
}
}
}
public void displayPoints() {
for (int i = 0; i < this.MAX_POINTS; i++) {
JOptionPane.showMessageDialog(null, "Point number " + (i + 1) + " is: " + this.coordinateList.get(i));
}
}
/**
* This sorts the points by the X coordinates
*/
public void sortByXCoordinates() {
Collections.sort(this.coordinateList, new PointCompare());
}
public class PointCompare
implements Comparator<Point> {
public int compare(final Point a, final Point b) {
if (a.x < b.x) {
return -1;
}
else if (a.x > b.x) {
return 1;
}
else {
return 0;
}
}
}
public static void main(final String[] args) {
final MainClass main = new MainClass();
main.inputCoordinates();
main.displayPoints();
}
}
i'm going to ignore all of the code you posted because you've just dumped everything without taking the time to identify the relevant areas.
now, from your question: you have an ArrayList containing Points. You want to sort it by the X axis/value.
List<Point> list = new ArrayList<Point>();
Firstly you need a Comparator which will compare one Point to another.
Comparator<Point> comp = new Comparator<Point>()
{
#Override
public int compare(Point o1, Point o2)
{
return new Integer(o1.x).compareTo(o2.x);
}
};
I choose to "box" the int to an Integer and use Integer's compareTo method. You could come up with a tidier method of comparison, up to you.
Then you can use the utility method Collections.sort
Collections.sort(list, comp);
and your list is sorted.
I'm using the Point Class to manage a list of (x,y) coordinates and I need to sort them in order of X
You can use a Bean Comparator or a custom Comparator as described in the blog.
The ArrayList class (see API documentation: http://download.oracle.com/javase/1.5.0/docs/api/java/util/ArrayList.html) that you use for your 'coordinateList' does not have a sort() method. You will have to implement this yourself, or use Collections.sort().

Categories

Resources