Test fixture wont initialise an array - java

I am trying to test my journey class methods, however, any method that uses the jArray field gives a null pointer exception as the arraylist has not actually been created. I was under the impression that my test fixture would address this yet the problem persists, any help appreciated.
private buscard.Journey tj1;
private buscard.Journey tj2;
/**
* Default constructor for test class JourneyTest
*/
public JourneyTest()
{
tj1 = new buscard.Journey(20120101, 120000, "74", 1);
tj2 = new buscard.Journey(20120102, 120000, "74", 1);
ArrayList<Journey> jArray = new ArrayList<Journey>();
jArray.add(tj1);
}
/**
* Sets up the test fixture.
*
* Called before every test case method.
*/
protected void setUp()
{
tj1 = new buscard.Journey(20120101, 120000, "74", 1);
tj2 = new buscard.Journey(20120102, 120000, "74", 1);
ArrayList<Journey> jArray = new ArrayList<Journey>();
jArray.add(tj1);
}
public void testGetDate()
{
Journey testJ1 = new Journey(20120101, 12.00, "74", 1);
assertEquals(20120101, testJ1.getDate());
}
public void testGetTime(){
Journey testJ1 = new Journey(20120101, 12.00, "74", 1);
assertEquals(12.0, testJ1.getTime());
}
public void testGetBusNumber(){
Journey testJ1 = new Journey(20120101, 12.00, "74", 1);
assertEquals("74", testJ1.getBusNumber());
}
public void testConstructor(){
Journey testJ1 = new Journey(20120101, 12.00, "74", 1);
assertEquals("74", testJ1.getBusNumber());
assertEquals(12.0, testJ1.getTime());
assertEquals(20120101, testJ1.getDate());
}
}
package buscard;
import java.util.ArrayList;
/**
* Write a description of class journey here.
*
* #author (your name)
* #version (a version number or a date)
*/
class Journey
{
public int date;
public double time;
public String busNumber;
public int journeyType;
public static double dayCharge = 0;
public static final double maxDayCharge = 3.50;
public static double weekCharge = 0;
public static final double maxWeekCharge = 15;
public static double monthCharge = 0;
public static final double maxMonthCharge = 48;
private int journeyNumber;
private static int numberOfJourneys = 0;
public double costOfJourney;
public static ArrayList<Journey> jArray;
public Journey(int date, double time, String busNumber, int journeyType)
{
this.date = date;
this.time = time;
this.busNumber = busNumber;
this.journeyType = journeyType;
journeyNumber = ++numberOfJourneys;
}
static
{
ArrayList<Journey> jArray = new ArrayList<Journey>();
}
public int getDate(){
return date;
}
public double getTime(){
return time;
}
public String getBusNumber(){
return busNumber;
}
public double getCostOfJourney(){
return costOfJourney;
}
public int getJourneyType(){
return journeyType;
}
public boolean isInSequence(int date, double time){
Journey prevJourney = jArray.get(jArray.size()-1);
return((prevJourney.getDate() < date)||(prevJourney.getDate() == date && prevJourney.time < time));
}
public static double returnLeast(){
double d = maxDayCharge - dayCharge;
double m = maxMonthCharge - monthCharge;
double w = maxWeekCharge - weekCharge;
double least = 0;
if (d <= w && d <= m)
{
least = d;
}
else if(w <= d && w <= m)
{
least = w;
}
else if(m <= d && m <= w)
{
least = m;
}
return least;
}
public double journeyCost(Journey reqJourney){
if (journeyType == 1){
if (dayCharge <= 2.50 && weekCharge <= 14 && monthCharge <= 47)
{
costOfJourney = 1;
}
else
{
costOfJourney = returnLeast();
}
}
else if (journeyType == 2)
{
if (dayCharge <= 1.80 && weekCharge <= 13.30 && monthCharge <= 46.30)
{
costOfJourney = 1.70;
}
else
{
costOfJourney = returnLeast();
}
}
else if (journeyType == 3)
{
if (dayCharge <= 1.60 && weekCharge <= 13.10 && monthCharge <= 46.10)
{
costOfJourney = 1.90;
}
else
{
costOfJourney = returnLeast();
}
}
return costOfJourney;
}
public static void updateCurrentCharges(int date){
int newDayOfYear = DateFunctions.getYearDay(date);
int newWeekOfYear = DateFunctions.getYearWeek(date);
int newMonthOfYear = DateFunctions.getYearMonth(date);
if (newDayOfYear > WmBusPass.dayOfYear)
{
WmBusPass.dayOfYear = newDayOfYear;
dayCharge = 0;
}
if (newWeekOfYear > WmBusPass.weekOfYear)
{
WmBusPass.weekOfYear = newWeekOfYear;
weekCharge = 0;
}
if (newMonthOfYear > WmBusPass.monthOfYear)
{
WmBusPass.monthOfYear = newMonthOfYear;
monthCharge = 0;
}
}
}

jArray is static field of Journey class.
You should replace
ArrayList<Journey> jArray = new ArrayList<Journey>();
with
buscard.Journey.jArray = new ArrayList<Journey>();

Related

Unexpected error with my class

When writing a class it is giving me an expected token error and I can not figure out how to solve it or why it is giving it to me.
Here's the code:
public class SetUpDoors {
private int DoorAmount;
private int WinningDoorAmount;
private int[] DoorArray= new int[DoorAmount];
private int winnerSelect = 0;
for (int i = 0; i < DoorAmount; i++) {
if (WinningDoorAmount > 0) {
winnerSelect = (int) Math.round( Math.random());
DoorArray[i] = winnerSelect;
if(winnerSelect == 1) {
WinningDoorAmount--;
}
}
else {
DoorArray[i] = 0;
}
DoorAmount--;
}
void setDoorAmount(int userDoors){
DoorAmount = userDoors;
}
void setWinningDoorAmount(int userWinningDoors) {
WinningDoorAmount = userWinningDoors;
}
}
it is giving the error on the ; at the end of private int winnerSelect = 0;
and an error for the } right below DoorAmount--;
The first is expected token "{" and the second is add "}" to complete block.
You must declare following code inside a method.
For example:
public void newMethod(){
for (int i = 0; i < DoorAmount; i++) {
if (WinningDoorAmount > 0) {
winnerSelect = (int) Math.round( Math.random());
DoorArray[i] = winnerSelect;
if(winnerSelect == 1) {
WinningDoorAmount--;
}
}
}
else {
DoorArray[i] = 0;
}
DoorAmount--;
}
try this
public class SetUpDoors {
private int DoorAmount;
private int WinningDoorAmount;
private int[] DoorArray= new int[DoorAmount];
private int winnerSelect = 0;
{
for (int i = 0; i < DoorAmount; i++) {
if (WinningDoorAmount > 0) {
winnerSelect = (int) Math.round( Math.random());
DoorArray[i] = winnerSelect;
if(winnerSelect == 1) {
WinningDoorAmount--;
}
}
else {
DoorArray[i] = 0;
}
DoorAmount--;
}
}
void setDoorAmount(int userDoors){
DoorAmount = userDoors;
}
void setWinningDoorAmount(int userWinningDoors) {
WinningDoorAmount = userWinningDoors;
}
}

random and time adequacy

I try to do my own version of "fruit ninja" for training based on this version : https://github.com/emmaguy/FruitNinja
I have done some minor changes. What I want to do is to affect different scores to the object in the "enum" in fruittype.
So, I add this function (in the aim to retrieve the current random value):
public static int currentrandom() {
return random.nextInt(FruitType2.values().length );
}
and I add,
if (FruitType2.currentrandom()<=9) {
score++;
} else {
score=score-5;
}
at the end of FruitProjectileManager.
Complete code for FruitProjectileManager:
public class FruitProjectileManager02 implements ProjectileManager {
private final Random random2 = new Random();
private final List<Projectile> fruitProjectiles =
new ArrayList<Projectile>();
private final SparseArray<Bitmap> bitmapCache;
private Region clip;
private int maxWidth;
private int maxHeight;
private String FruitTypen = "FruitType2";
public FruitProjectileManager02(Resources r) {
bitmapCache = new SparseArray<Bitmap>(FruitType2.values().length);
for (FruitType2 t : FruitType2.values()) {
bitmapCache.put(t.getResourceId(), BitmapFactory.decodeResource(r, t.getResourceId(), new Options()));
}
}
public void draw(Canvas canvas) {
for (Projectile f : fruitProjectiles) {
f.draw(canvas);
}
}
public void update() {
if (maxWidth < 0 || maxHeight < 0) {
return;
}
if (random2.nextInt(1000) < 30) {
fruitProjectiles.add(createNewFruitProjectile());
}
for (Iterator<Projectile> iter = fruitProjectiles.iterator(); iter.hasNext(); ) {
Projectile f = iter.next();
f.move();
if (f.hasMovedOffScreen()) {
iter.remove();
}
}
}
private FruitProjectile02 createNewFruitProjectile() {
int angle = random2.nextInt(20) + 70;
int speed = random2.nextInt(30) + 120;
boolean rightToLeft = random2.nextBoolean();
float gravity = random2.nextInt(6) + 8.0f;
float rotationStartingAngle = random2.nextInt(360);
float rotationIncrement = random2.nextInt(100) / 3.0f;
if (random2.nextInt(1) % 2 == 0) {
rotationIncrement *= -1;
}
return new FruitProjectile02(bitmapCache.get(FruitType2.randomFruit().getResourceId()), maxWidth, maxHeight,
angle, speed, gravity, rightToLeft, rotationIncrement, rotationStartingAngle);
}
public void setWidthAndHeight(int width, int height) {
this.maxWidth = width;
this.maxHeight = height;
this.clip = new Region(0, 0, width, height);
}
#Override
public int testForCollisions(List<TimedPath> allPaths) {
int score = 0;
for (TimedPath p : allPaths) {
for (Projectile f : fruitProjectiles) {
if (!f.isAlive())
continue;
Region projectile = new Region(f.getLocation());
Region path = new Region();
path.setPath(p, clip);
if (!projectile.quickReject(path) && projectile.op(path, Region.Op.INTERSECT)) {
if (FruitType2.currentrandom() <= 9) {
score++;
} else {
score = score - 5;
}
f.kill();
}
}
}
return score;
}
}
Complete code for FruitType:
public enum FruitType2 {
T02(R.drawable.n002),
T04(R.drawable.n004),
T06(R.drawable.n006),
T08(R.drawable.n008),
T10(R.drawable.n010),
T12(R.drawable.n012),
T14(R.drawable.n014),
T16(R.drawable.n016),
T18(R.drawable.n018),
T20(R.drawable.n020),
OTHER1(R.drawable.n003),
OTHER2(R.drawable.n007),
OTHER3(R.drawable.n011);
private final int resourceId;
private FruitType2(int resourceId) {
this.resourceId = resourceId;
}
public int getResourceId() {
return resourceId;
}
private static final Random random = new Random();
public static int currentrandom() {
return random.nextInt(FruitType2.values().length);
}
public static FruitType2 randomFruit() {
return FruitType2.values()[random.nextInt(FruitType2.values().length)];
}
}
I understand the problem , the current random(when the fruit is generated) is not the same that the random when the fruit is sliced and my question is how to
solve this problem. I get no idea so if you have some clues, I am interested.
Thank you in advance.
Perhaps i don't understand the problem, but why don't you store the random number in a variable? Later you can take the random number out of the variable.

JavaFX: scrollview swipe effect

I would like to know, how to make scrollview swipe effect when mouse is dragged up and down. I'm developing JavaFX application which has ListView & I need to scroll the list when user drags the mouse up and down (like iOS contact list).
Also how to add the user's dragging velocity and speed to the scrolling value?
UPDATED : I got some code here but It doesn't work properly...
import java.util.ArrayList;
import java.util.Arrays;
import javafx.animation.Interpolator;
import javafx.animation.KeyFrame;
import javafx.animation.KeyValue;
import javafx.animation.Timeline;
import javafx.animation.TimelineBuilder;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.event.Event;
import javafx.geometry.Pos;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollPane;
import javafx.scene.input.MouseEvent;
import javafx.scene.input.ScrollEvent;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.FlowPane;
import javafx.util.Duration;
public class Swipe extends ScrollPane {
private static final int INERTIA_DURATION = 2400;
private static final double CLICK_THRESHOLD = 20;
private static final double CLICK_TIME_THRESHOLD = Integer.parseInt(System.getProperty("click", "400"));
private final double width;
private final double height;
private long startDrag;
private long lastDrag;
private long lastDragDelta;
private int startDragX;
private int startDragY;
private int lastDragX;
private int lastDragY;
private int lastDragStepX;
private int lastDragStepY;
private double dragVelocityX;
private double dragVelocityY;
private boolean clickThresholdBroken;
private Timeline inertiaTimeline = null;
private long lastClickTime = -1;
private final boolean isFiredByMe = false;
public Swipe(double width, double height) {
this.width = width;
this.height = height;
init();
}
private void init() {
setPrefSize(width, height);
setPannable(true);
setHbarPolicy(ScrollBarPolicy.NEVER);
setVbarPolicy(ScrollBarPolicy.NEVER);
setEventHandlers();
ContentPane cp = new ContentPane();
setContent(cp);
}
private void setEventHandlers() {
setOnMousePressed((MouseEvent event) -> {
lastDragX = startDragX = (int) event.getX();
lastDragY = startDragY = (int) event.getY();
lastDrag = startDrag = System.currentTimeMillis();
lastDragDelta = 0;
if (inertiaTimeline != null) {
inertiaTimeline.stop();
}
clickThresholdBroken = false;
});
setOnDragDetected((MouseEvent event) -> {
// Delta of this drag vs. last drag location (or start)
lastDragStepX = (int) event.getX() - lastDragX;
lastDragStepY = (int) event.getY() - lastDragY;
// Duration of this drag step.
lastDragDelta = System.currentTimeMillis() - lastDrag;
// Velocity of last drag increment.
dragVelocityX = (double) lastDragStepX / (double) lastDragDelta;
dragVelocityY = (double) lastDragStepY / (double) lastDragDelta;
// Snapshot of this drag event.
lastDragX = (int) event.getX();
lastDragY = (int) event.getY();
lastDrag = System.currentTimeMillis();
// Calculate distance so far -- have we dragged enough to scroll?
final int dragX = (int) event.getX() - startDragX;
final int dragY = (int) event.getY() - startDragY;
double distance = Math.abs(Math.sqrt((dragX * dragX) + (dragY * dragY)));
int scrollDistX = lastDragStepX;
int scrollDistY = lastDragStepY;
if (!clickThresholdBroken && distance > CLICK_THRESHOLD) {
clickThresholdBroken = true;
scrollDistX = dragX;
scrollDistY = dragY;
}
if (clickThresholdBroken) {
Event.fireEvent(event.getTarget(), new ScrollEvent(
ScrollEvent.SCROLL,
scrollDistX, scrollDistY,
scrollDistX, scrollDistY,
event.isShiftDown(), event.isControlDown(), event.isAltDown(), event.isMetaDown(),
true, false,
event.getX(), event.getY(),
event.getSceneX(), event.getSceneY(),
ScrollEvent.HorizontalTextScrollUnits.NONE, 0,
ScrollEvent.VerticalTextScrollUnits.NONE, 0, 0, null));
}
});
setOnMouseReleased((MouseEvent event) -> {
handleRelease(event);
});
setOnMouseClicked((MouseEvent event) -> {
final long time = System.currentTimeMillis();
if (clickThresholdBroken || (lastClickTime != -1 && (time - lastClickTime) < CLICK_TIME_THRESHOLD)) {
event.consume();
}
lastClickTime = time;
});
}
private void handleRelease(final MouseEvent me) {
if (clickThresholdBroken) {
// Calculate last instantaneous velocity. User may have stopped moving
// before they let go of the mouse.
final long time = System.currentTimeMillis() - lastDrag;
dragVelocityX = (double) lastDragStepX / (time + lastDragDelta);
dragVelocityY = (double) lastDragStepY / (time + lastDragDelta);
// determin if click or drag/flick
final int dragX = (int) me.getX() - startDragX;
final int dragY = (int) me.getY() - startDragY;
// calculate complete time from start to end of drag
final long totalTime = System.currentTimeMillis() - startDrag;
// if time is less than 300ms then considered a quick flick and whole time is used
final boolean quick = totalTime < 300;
// calculate velocity
double velocityX = quick ? (double) dragX / (double) totalTime : dragVelocityX; // pixels/ms
double velocityY = quick ? (double) dragY / (double) totalTime : dragVelocityY; // pixels/ms
final int distanceX = (int) (velocityX * INERTIA_DURATION); // distance
final int distanceY = (int) (velocityY * INERTIA_DURATION); // distance
//
DoubleProperty animatePosition = new SimpleDoubleProperty() {
double lastMouseX = me.getX();
double lastMouseY = me.getY();
#Override
protected void invalidated() {
final double mouseX = me.getX() + (distanceX * get());
final double mouseY = me.getY() + (distanceY * get());
final double dragStepX = mouseX - lastMouseX;
final double dragStepY = mouseY - lastMouseY;
if (Math.abs(dragStepX) >= 1.0 || Math.abs(dragStepY) >= 1.0) {
Event.fireEvent(me.getTarget(), new ScrollEvent(
ScrollEvent.SCROLL,
dragStepX, dragStepY,
(distanceX * get()), (distanceY * get()),
me.isShiftDown(), me.isControlDown(), me.isAltDown(), me.isMetaDown(),
true, true,
me.getX(), me.getY(),
me.getSceneX(), me.getSceneY(),
ScrollEvent.HorizontalTextScrollUnits.NONE, 0,
ScrollEvent.VerticalTextScrollUnits.NONE, 0,
0, null));
}
lastMouseX = mouseX;
lastMouseY = mouseY;
}
};
// animate a slow down from current velocity to zero
inertiaTimeline = TimelineBuilder.create()
.keyFrames(
new KeyFrame(Duration.ZERO, new KeyValue(animatePosition, 0)),
new KeyFrame(Duration.millis(INERTIA_DURATION), new KeyValue(animatePosition, 1d, Interpolator.SPLINE(0.0513, 0.1131, 0.1368, 1.0000)))
).build();
inertiaTimeline.play();
}
}
private class ContentPane extends FlowPane {
private ArrayList getList() {
String[] list = {
"Kerrie Batts", "Raina Huffstutler", "Kip Kukowski", "Trish Sullivan", "Kyla Hollingsworth", "Gearldine Leavy", "Major Langdon", "Avery Rusin", "Hedy Messina", "Audry Felps", "Tianna Robbins", "Marian Tranmer", "Lashaunda Bivona", "Leighann Schwab", "Emanuel Volpe", "Neida Geist", "Edda Placencia", "Olevia Hippe", "Fernando Cohen", "Danette Dorsett"};
ArrayList<String> nameList = new ArrayList();
nameList.addAll(Arrays.asList(list));
return nameList;
}
public ContentPane() {
setPrefSize(215, 271);
ArrayList<String> nameList = getList();
Element[] element = new Element[nameList.size()];
for (int i = 0; i < nameList.size(); i++) {
String name = nameList.get(i);
Element el = element[i] = new Element(210, 25, name);
getChildren().add(el);
}
}
}
private class Element extends AnchorPane {
private double width;
private double height;
private String name;
public Element(double width, double height, String name) {
this.width = width;
this.height = height;
this.name = name;
init();
}
private Label createName() {
Label label = new Label(name);
label.setPrefSize(width, height);
label.setAlignment(Pos.CENTER_LEFT);
AnchorPane.setLeftAnchor(label, 5.0);
label.setStyle("-fx-font-family: Calibri; -fx-font-size: 14;");
return label;
}
private void init() {
setPrefSize(width, height);
getChildren().add(createName());
}
public void setPrefSize(double width, double height) {
this.width = width;
this.height = height;
}
public void setName(String name) {
this.name = name;
}
}
}
I figured out myself. There is two classes. 1st one is for calculate the velocity of the movement.
VelocityTracker.java
import javafx.scene.input.MouseEvent;
public final class VelocityTracker {
private static final boolean DEBUG = false;
private static final boolean localLOGV = DEBUG;
private static final int NUM_PAST = 10;
private static final int MAX_AGE_MILLISECONDS = 200;
private static final int POINTER_POOL_CAPACITY = 20;
private static Pointer sRecycledPointerListHead;
private static int sRecycledPointerCount;
private static final class Pointer {
public Pointer next;
public int id;
public float xVelocity;
public float yVelocity;
public final float[] pastX = new float[NUM_PAST];
public final float[] pastY = new float[NUM_PAST];
public final long[] pastTime = new long[NUM_PAST]; // uses Long.MIN_VALUE as a sentinel
}
private Pointer mPointerListHead; // sorted by id in increasing order
private int mLastTouchIndex;
public VelocityTracker() {
clear();
}
public void clear() {
releasePointerList(mPointerListHead);
mPointerListHead = null;
mLastTouchIndex = 0;
}
public void addMovement(MouseEvent ev) {
final int historySize = 0;
final int lastTouchIndex = mLastTouchIndex;
final int nextTouchIndex = (lastTouchIndex + 1) % NUM_PAST;
final int finalTouchIndex = (nextTouchIndex + historySize) % NUM_PAST;
mLastTouchIndex = finalTouchIndex;
if (mPointerListHead == null) {
mPointerListHead = obtainPointer();
}
final float[] pastX = mPointerListHead.pastX;
final float[] pastY = mPointerListHead.pastY;
final long[] pastTime = mPointerListHead.pastTime;
pastX[finalTouchIndex] = (float) ev.getX();
pastY[finalTouchIndex] = (float) ev.getY();
pastTime[finalTouchIndex] = System.currentTimeMillis();
}
public void computeCurrentVelocity(int units) {
computeCurrentVelocity(units, Float.MAX_VALUE);
}
public void computeCurrentVelocity(int units, float maxVelocity) {
final int lastTouchIndex = mLastTouchIndex;
for (Pointer pointer = mPointerListHead; pointer != null; pointer = pointer.next) {
final long[] pastTime = pointer.pastTime;
int oldestTouchIndex = lastTouchIndex;
int numTouches = 1;
final long minTime = pastTime[lastTouchIndex] - MAX_AGE_MILLISECONDS;
while (numTouches < NUM_PAST) {
final int nextOldestTouchIndex = (oldestTouchIndex + NUM_PAST - 1) % NUM_PAST;
final long nextOldestTime = pastTime[nextOldestTouchIndex];
if (nextOldestTime < minTime) { // also handles end of trace sentinel
break;
}
oldestTouchIndex = nextOldestTouchIndex;
numTouches += 1;
}
if (numTouches > 3) {
numTouches -= 1;
}
final float[] pastX = pointer.pastX;
final float[] pastY = pointer.pastY;
final float oldestX = pastX[oldestTouchIndex];
final float oldestY = pastY[oldestTouchIndex];
final long oldestTime = pastTime[oldestTouchIndex];
float accumX = 0;
float accumY = 0;
for (int i = 1; i < numTouches; i++) {
final int touchIndex = (oldestTouchIndex + i) % NUM_PAST;
final int duration = (int) (pastTime[touchIndex] - oldestTime);
if (duration == 0) {
continue;
}
float delta = pastX[touchIndex] - oldestX;
float velocity = (delta / duration) * units; // pixels/frame.
accumX = (accumX == 0) ? velocity : (accumX + velocity) * .5f;
delta = pastY[touchIndex] - oldestY;
velocity = (delta / duration) * units; // pixels/frame.
accumY = (accumY == 0) ? velocity : (accumY + velocity) * .5f;
}
if (accumX < -maxVelocity) {
accumX = -maxVelocity;
} else if (accumX > maxVelocity) {
accumX = maxVelocity;
}
if (accumY < -maxVelocity) {
accumY = -maxVelocity;
} else if (accumY > maxVelocity) {
accumY = maxVelocity;
}
pointer.xVelocity = accumX;
pointer.yVelocity = accumY;
}
}
public float getXVelocity() {
Pointer pointer = getPointer(0);
return pointer != null ? pointer.xVelocity : 0;
}
public float getYVelocity() {
Pointer pointer = getPointer(0);
return pointer != null ? pointer.yVelocity : 0;
}
public float getXVelocity(int id) {
Pointer pointer = getPointer(id);
return pointer != null ? pointer.xVelocity : 0;
}
public float getYVelocity(int id) {
Pointer pointer = getPointer(id);
return pointer != null ? pointer.yVelocity : 0;
}
private Pointer getPointer(int id) {
for (Pointer pointer = mPointerListHead; pointer != null; pointer = pointer.next) {
if (pointer.id == id) {
return pointer;
}
}
return null;
}
private static Pointer obtainPointer() {
if (sRecycledPointerCount != 0) {
Pointer element = sRecycledPointerListHead;
sRecycledPointerCount -= 1;
sRecycledPointerListHead = element.next;
element.next = null;
return element;
}
return new Pointer();
}
private static void releasePointer(Pointer pointer) {
if (sRecycledPointerCount < POINTER_POOL_CAPACITY) {
pointer.next = sRecycledPointerListHead;
sRecycledPointerCount += 1;
sRecycledPointerListHead = pointer;
}
}
private static void releasePointerList(Pointer pointer) {
if (pointer != null) {
int count = sRecycledPointerCount;
if (count >= POINTER_POOL_CAPACITY) {
return;
}
Pointer tail = pointer;
for (;;) {
count += 1;
if (count >= POINTER_POOL_CAPACITY) {
break;
}
Pointer next = tail.next;
if (next == null) {
break;
}
tail = next;
}
tail.next = sRecycledPointerListHead;
sRecycledPointerCount = count;
sRecycledPointerListHead = pointer;
}
}
}
And this is second class
import java.util.concurrent.atomic.AtomicReference;
import javafx.animation.FadeTransition;
import javafx.animation.Interpolator;
import javafx.animation.Timeline;
import javafx.animation.TranslateTransition;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.beans.value.ObservableValue;
import javafx.geometry.Bounds;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Region;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.util.Duration;
public class VerticlePane extends Region {
private ObjectProperty<Node> content;
private final VelocityTracker tracker = new VelocityTracker();
private final Rectangle clipRect = new Rectangle();
private Rectangle scrollNode;
private boolean magnet, autoTranslate = true;
private DoubleProperty targetY = new SimpleDoubleProperty(), controlHeight = new SimpleDoubleProperty(), viewHeight = new SimpleDoubleProperty();
private double startValue, endValue;
private HBox indicator;
private StringProperty indicatorValue = new SimpleStringProperty("Pull Up to Update...");
public VerticlePane() {
setFocusTraversable(false);
setClip(clipRect);
contentProperty().addListener((ObservableValue<? extends Node> observable, Node oldValue, Node newValue) -> {
getChildren().clear();
if (newValue != null) {
getChildren().addAll(newValue, createRectangle());
}
layout();
});
final AtomicReference<MouseEvent> deltaEvent = new AtomicReference<>();
final AtomicReference<TranslateTransition> currentTransition1 = new AtomicReference<>();
final AtomicReference<TranslateTransition> currentTransition2 = new AtomicReference<>();
final AtomicReference<Timeline> timeline = new AtomicReference<>();
setOnMousePressed((me) -> {
tracker.addMovement(me);
deltaEvent.set(me);
startValue = me.getY();
if (currentTransition1.get() != null) {
currentTransition1.get().stop();
}
if (currentTransition2.get() != null) {
currentTransition2.get().stop();
}
if (timeline.get() != null) {
timeline.get().stop();
}
});
setOnMouseDragged((event) -> {
tracker.addMovement(event);
double delta = event.getY() - deltaEvent.get().getY();
targetY.set(content.get().getTranslateY() + delta);
content.get().setTranslateY(targetY.get());
controlHeight.set(content.get().getLayoutBounds().getHeight());
viewHeight.set(getHeight());
double scrollTargetY = targetY.divide(controlHeight.divide(viewHeight.get()).get()).get();
double lastInstanceHeight = controlHeight.subtract(viewHeight.get()).multiply(-1).get();
scrollNode.relocate(1.0, (getHeight() - 5.0));
scrollNode.setArcHeight(5.0);
scrollNode.setArcWidth(5.0);
scrollNode.setHeight(viewHeight.divide(controlHeight.divide(viewHeight.get()).get()).get());
scrollNode.setVisible(true);
scrollNode.setOpacity(0.25);
if (targetY.lessThan(0).and(targetY.greaterThan(lastInstanceHeight)).get()) {
scrollNode.setTranslateY(Math.abs(scrollTargetY));
} else if (targetY.greaterThanOrEqualTo(0).get()) {
scrollNode.setHeight(scrollNode.getHeight() - targetY.get());
}
if (targetY.get() < lastInstanceHeight) {
double scrollNodeHeight = scrollNode.getHeight() - (lastInstanceHeight - targetY.get());
double scrollNodeTranslateY = viewHeight.subtract(viewHeight.divide(controlHeight.divide(viewHeight.get()).get()).get()).add(lastInstanceHeight - targetY.get()).get();
scrollNode.setHeight(scrollNodeHeight);
scrollNode.setTranslateY(scrollNodeTranslateY);
}
deltaEvent.set(event);
});
setOnMouseReleased((me) -> {
FadeTransition ft = new FadeTransition(Duration.millis(300), scrollNode);
ft.setFromValue(0.25);
ft.setToValue(0.00);
tracker.addMovement(me);
tracker.computeCurrentVelocity(500);
endValue = me.getY();
controlHeight.set(content.get().getLayoutBounds().getHeight());
viewHeight.set(getHeight());
float velocityY = tracker.getYVelocity();
targetY.set(scrollNode(velocityY, currentTransition1, content.get()));
TranslateTransition tt = bb(currentTransition2, scrollNode, Math.abs((targetY.divide(controlHeight.divide(viewHeight.get()).get()).get())));
tt.setOnFinished((ae) -> {
ft.play();
});
});
}
public double getStartValue() {
return startValue;
}
public double getEndValue() {
return endValue;
}
public double getControlHeight() {
return controlHeight.get();
}
public double getViewHeight() {
return viewHeight.get();
}
public VerticlePane(double prefWidth, double prefHeight) {
this();
setPrefSize(prefWidth, prefHeight);
}
public VerticlePane(double prefWidth, double prefHeight, boolean magnet) {
this(prefWidth, prefHeight);
setMagnet(magnet);
}
public final void setMagnet(boolean magnet) {
this.magnet = magnet;
}
private TranslateTransition bb(AtomicReference<TranslateTransition> currentTransition, Node node, Double targetY) {
TranslateTransition translate = new TranslateTransition(new Duration(1000), node);
if (node != null) {
translate.setInterpolator(Interpolator.SPLINE(0.0513, 0.1131, 0.1368, 1.0000));
if (targetY != null) {
translate.setFromY(node.getTranslateY());
translate.setToY(targetY);
}
translate.play();
currentTransition.set(translate);
}
return translate;
}
private Double scrollNode(float velocityY, AtomicReference<TranslateTransition> currentTransition, Node node) {
final Bounds b = node.getLayoutBounds();
Double backBouncingY = null;
Double targetY = null;
if (node != null) {
TranslateTransition translate = new TranslateTransition(new Duration(1000), node);
translate.setInterpolator(Interpolator.SPLINE(0.0513, 0.1131, 0.1368, 1.0000));
if (Math.abs(velocityY) < 10) {
velocityY = 0;
}
targetY = node.getTranslateY();
double controlHeight = b.getHeight() - indicator.heightProperty().add(10).get();
double viewHeight = getHeight();
if (controlHeight < viewHeight && targetY < controlHeight) {
targetY = 0.0;
} else if (targetY > 0) {
targetY = 0.0;
} else if ((targetY < (controlHeight - viewHeight) * -1)) {
targetY = (controlHeight - viewHeight) * -1;
} else {
targetY += velocityY;
if (controlHeight < viewHeight && targetY < controlHeight) {
targetY = -25.0;
backBouncingY = 0.0;
} else if (targetY > 0) {
targetY = 25.0;
backBouncingY = 0.0;
} else if (targetY < (controlHeight - viewHeight) * -1) {
targetY = (controlHeight - viewHeight) * -1 - 25;
backBouncingY = (controlHeight - viewHeight) * -1;
}
}
//Magnet
if (magnet) {
double dragRegion = (viewHeight / 2) * -1;
double instances = controlHeight / viewHeight;
double lastInstance = ((controlHeight - viewHeight) * -1);
double newInstanceValue = dragRegion;
if (targetY > dragRegion) {
targetY = 0.0;
}
if (instances > 1) {
for (int i = 1; i < instances - 1; i++) {
double instanceValue = (viewHeight * i) * -1;
if (targetY < newInstanceValue && targetY > instanceValue || targetY < instanceValue && targetY > (instanceValue + dragRegion)) {
targetY = instanceValue;
}
newInstanceValue += (viewHeight * -1);
}
}
if (targetY < (lastInstance - dragRegion) && targetY > lastInstance) {
targetY = lastInstance;
}
}
//
if (targetY != null) {
translate.setFromY(node.getTranslateY());
translate.setToY(targetY);
}
if (backBouncingY != null) {
final Double fbackFlingY = backBouncingY;
translate.setOnFinished((ae) -> {
currentTransition.set(null);
TranslateTransition translate1 = new TranslateTransition(new Duration(300), node);
if (fbackFlingY != null) {
translate1.setFromY(node.getTranslateY());
translate1.setToY(fbackFlingY);
}
translate1.play();
currentTransition.set(translate1);
});
} else {
translate.setOnFinished((ae) -> {
currentTransition.set(null);
});
}
translate.play();
currentTransition.set(translate);
}
return targetY;
}
private Rectangle createRectangle() {
if (scrollNode == null) {
scrollNode = new Rectangle(4.0, 4.0, Color.BLACK);
}
scrollNode.setVisible(false);
return scrollNode;
}
public ObjectProperty<Node> contentProperty() {
if (content == null) {
content = new SimpleObjectProperty<>(this, "content");
}
return content;
}
public final void setContent(Node value) {
contentProperty().set(
new VBox(10) {
{
getChildren().addAll(value, indicator());
}
}
);
contentProperty().get().layoutBoundsProperty().addListener((ObservableValue<? extends Bounds> obs, Bounds ov, Bounds nv) -> {
Double containerHeight = nv.getHeight();
Double flingHeight = prefHeightProperty().get();
if (autoTranslate) {
if (flingHeight <= containerHeight) {
contentProperty().get().setTranslateY((containerHeight - flingHeight - 34) * -1);
}
}
});
}
private HBox indicator() {
return indicator = new HBox(10) {
{
setVisible(false);
setAlignment(Pos.CENTER);
getChildren().addAll(
new ImageView(new Image(getClass().getResourceAsStream("Indicator.gif"))),
new Label() {
{
textProperty().bind(indicatorValue);
setStyle("-fx-font-family: Roboto; -fx-font-size: 14px;");
}
}
);
}
};
}
public void setAutoTranslate(Boolean autoTranslate) {
this.autoTranslate = autoTranslate;
}
public void setTranslateZero() {
this.contentProperty().get().setTranslateY(0);
}
public HBox getIndicator() {
return indicator;
}
public void showIndicator() {
indicator.setVisible(true);
}
public void hideIndicator() {
indicator.setVisible(false);
}
public void setIndicatorValue(String value) {
indicatorValue.setValue(value);
}
public final Node getContent() {
return content == null ? null : content.get();
}
#Override
protected void layoutChildren() {
super.layoutChildren();
clipRect.setWidth(getWidth());
clipRect.setHeight(getHeight());
}
}
Scroll Bar disabled why?
It should not extend:
public class VerticlePane extends Control

Array-based implementation of a sorted linked list

I need to write a java linked list which needs to be array based and sorted. So the array contains nodes which have 2 fields: the data, and the index of the next element in the list. The last element of the list needs to have an index of -1.
Can someone help how to add an element to such list. this is the code I wrote so far but does not seems to be right because I can add elements but the indexes are not right.
package listpackage;
import java.io.IOException;
public class ArrayLL {
private int MAX_CAP = 100;
private ANode[] list;
private int size;
public ArrayLL(){
list = new ANode[MAX_CAP];
list[list.length-1] = new ANode(null, -1);
for(int i = 0; i < list.length-1; i++){
list[i] = new ANode(null, i+1);
}
size = 0;
}
public void addElem(String s) throws IOException{
if(this.getSize() == 0){
ANode a = new ANode(s, -1);
list[0] = a;
}else if(size == MAX_CAP + 1){
throw new IOException("List is full");
}else{
int index = 0;
for(int i=0; i < list.length; i++){
if(list[i].getData() == null){
index = i;
break;
}
}
ANode b = new ANode(s);
list[index] = b;
if(this.getSize()==1){
if (list[index].getData().compareTo(list[0].getData()) < 0){
list[index].setLink(0);
list[0].setLink(-1);
}else{
list[index].setLink(-1);
list[0].setLink(index);
}
}else{
int i = 0;
while(list[i].getData() != null){
if(list[index].getData().compareTo(list[i].getData()) < 0){
list[index].setLink(i);
if(i>0)
list[i-1].setLink(index);
}else{
i++;
}
}
}
}
size++;
}
public ANode[] getList(){
return list;
}
public int getSize(){
return size;
}
}
class ANode{
private String data;
private int link;
public ANode(String d){
data = d;
link = -1;
}
public ANode(String d, int l){
data = d;
link = l;
}
public String getData(){
return data;
}
public int getLink(){
return link;
}
public void setLink(int l){
link = l;
}
}
It was fun to solve this tricky program... :-)... i enjoyed it...here is the working solution...I tested using various scenarios...
In order to make sure I do not change much of your code...I did not optimize the code..there are many places where code can be more simpler and readable...
import java.io.IOException;
public class ArrayLL {
public static void main(String[] args) throws IOException {
ArrayLL myList = new ArrayLL();
myList.addElem("c");
myList.addElem("b");
myList.addElem("a");
myList.addElem("d");
int i = myList.startOfListIndex;
while(myList.list[i].getLink()!=-1)
{
System.out.println(myList.list[i].getData());
i = myList.list[i].getLink();
}
System.out.println(myList.list[i].getData());
}
private int MAX_CAP = 100;
private ANode[] list;
private int size;
private int startOfListIndex = 0;
public ArrayLL() {
list = new ANode[MAX_CAP];
for (int i = 0; i < list.length; i++) {
list[i] = new ANode(null);
}
size = 0;
}
public void addElem(String s) throws IOException {
if (this.getSize() == 0) {
ANode a = new ANode(s, -1);
list[0] = a;
} else if (size == MAX_CAP + 1) {
throw new IOException("List is full");
} else {
int index = 0;
for (int i = 0; i < list.length; i++) {
if (list[i].getData() == null) {
index = i;
break;
}
}
ANode b = new ANode(s);
list[index] = b;
if (this.getSize() == 1) {
if (list[index].getData().compareTo(list[0].getData()) < 0) {
list[index].setLink(0);
list[0].setLink(-1);
startOfListIndex = index;
} else {
list[index].setLink(-1);
list[0].setLink(index);
}
} else {
int i = startOfListIndex;
int prevIndex = -1;
while (i!=-1 && list[i].getData() != null) {
if (list[index].getData().compareTo(list[i].getData()) < 0) {
list[index].setLink(i);
if(prevIndex!=-1)
list[prevIndex].setLink(index);
else
startOfListIndex = index;
break;
} else {
prevIndex = i;
i=list[i].getLink();
}
}
if(i==-1)
{
list[prevIndex].setLink(index);
}
}
}
size++;
}
public ANode[] getList() {
return list;
}
public int getSize() {
return size;
}
}
class ANode {
private String data;
private int link;
public ANode(String d) {
data = d;
link = -1;
}
public ANode(String d, int l) {
data = d;
link = l;
}
public String getData() {
return data;
}
public int getLink() {
return link;
}
public void setLink(int l) {
link = l;
}
}
This is the full solution i believe as it works for all the test i have done, but there might be something i haven't thought of. The solution includes the removeElem() method too.
package listpackage;
import java.io.IOException;
public class ArrayLL {
private int MAX_CAP = 100;
private ANode[] list;
private int size;
private int startOfListIndex = 0;
public ArrayLL() {
list = new ANode[MAX_CAP];
list[list.length-1] = new ANode(null, -1);
for(int i = 0; i < list.length-1; i++){
list[i] = new ANode(null, i+1);
}
size = 0;
}
public void addElem(String s) throws IOException {
if (this.getSize() == 0) {
ANode a = new ANode(s, -1);
list[0] = a;
}else if (size == MAX_CAP + 1) {
throw new IOException("List is full");
}else{
int index = 0;
for (int i = 0; i < list.length; i++) {
if (list[i].getData() == null) {
index = i;
break;
}
}
ANode b = new ANode(s);
list[index] = b;
if (this.getSize() == 1) {
if (list[index].getData().compareTo(list[0].getData()) < 0) {
list[index].setLink(0);
list[0].setLink(-1);
startOfListIndex = index;
} else {
list[index].setLink(-1);
list[0].setLink(index);
}
} else {
int i = startOfListIndex;
int prevIndex = -1;
while (i!=-1 && list[i].getData() != null) {
if (list[index].getData().compareTo(list[i].getData()) < 0) {
list[index].setLink(i);
if(prevIndex!=-1)
list[prevIndex].setLink(index);
else
startOfListIndex = index;
break;
}else{
prevIndex = i;
i=list[i].getLink();
}
}
if(i==-1)
{
list[prevIndex].setLink(index);
}
}
}
size++;
}
public void removeElem(String s) throws IOException {
if (this.getSize() == 0) {
throw new IOException("List is empty");
}else{
int firstEmpty = 0;
for(int i = 0; i< list.length; i++){
if(list[i].getData() == null){
firstEmpty = i;
break;
}
}
int elemindex = 0;
int prev = -1;
int next=-1;
for(int i = 0; i < list.length; i++){
if(list[i].getData() != null && list[i].getData().compareTo(s) == 0){
elemindex = i;
next = list[i].getLink();
for(int j = 0; j < list.length; j++){
if(list[j].getLink() == elemindex){
prev = j;
break;
}
}
list[elemindex].setDataNull();
list[elemindex].setLink(firstEmpty);
if(next != -1)
list[prev].setLink(next);
else
list[prev].setLink(-1);
size--;
}else{
elemindex++;
}
}
}
}
public ANode[] getList() {
return list;
}
public int getSize() {
return size;
}
}
class ANode {
private String data;
private int link;
public ANode(String d) {
data = d;
link = -1;
}
public ANode(String d, int l) {
data = d;
link = l;
}
public String getData() {
return data;
}
public void setDataNull(){
this.data = null;
}
public int getLink() {
return link;
}
public void setLink(int l) {
link = l;
}
}

"A Java Exception has occurred"

So I'm trying to run my pacman project as a jar(also tried runnable) and I just get the error message you see in the title. It runs perfectly fine in eclipse/netbeans, but whilst cleaning/building i see the warnings:
Note: C:\Users\Lucas\Documents\Eclipse\PackMan\src\game\packman\GameData.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
The main class is correct and assigned. Does anybody know what I'm doing wrong?
Here is my GameData class
public class GameData {
int mazeNo;
CopyOnWriteArrayList<Position> pills;
CopyOnWriteArrayList<Position> powerPills;
public MoverInfo packman;
public GhostInfo[] ghostInfos = new GhostInfo[4];
public int score;
Maze[] mazes;
boolean dead = false;
boolean win = false;
public GameData() {
mazes = new Maze[4];
// load mazes information
for (int m=0; m<4; m++) {
mazes[m] = new Maze(m);
}
setMaze(mazeNo);
}
private void setMaze(int m) {
packman = new MoverInfo(mazes[m].packmanPos);
for (int g=0; g<4; g++) {
ghostInfos[g] = new GhostInfo(mazes[m].ghostPos);
}
pills = new CopyOnWriteArrayList((List<Position>)(mazes[m].pills.clone()));
powerPills = new CopyOnWriteArrayList((List<Position>)(mazes[m].powerPills.clone()));
}
public void movePackMan(int reqDir) {
if (move(reqDir, packman)) {
packman.curDir = reqDir;
} else {
move(packman.curDir, packman);
}
}
private int wrap(int value, int incre, int max) {
return (value+max+incre)%max;
}
private boolean move(int reqDir, MoverInfo info) {
// current position of packman is (row, column)
int row = info.pos.row;
int column = info.pos.column;
int rows = mazes[mazeNo].rows;
int columns = mazes[mazeNo].columns;
int nrow = wrap(row, MoverInfo.DROW[reqDir], rows);
int ncol = wrap(column, MoverInfo.DCOL[reqDir], columns);
if (mazes[mazeNo].charAt(nrow, ncol) != '0') {
info.pos.row = nrow;
info.pos.column = ncol;
return true;
}
return false;
}
public void update() {
if (pills.contains(packman.pos)) {
pills.remove(packman.pos);
score += 5;
} else if (powerPills.contains(packman.pos)) {
powerPills.remove(packman.pos);
score += 50;
for (GhostInfo g:ghostInfos) {
g.edibleCountDown = 500;
}
}
for (GhostInfo g:ghostInfos) {
if (g.edibleCountDown > 0) {
if (touching(g.pos, packman.pos)) {
// eat the ghost and reset
score += 100;
g.curDir = g.reqDir = MoverInfo.LEFT;
g.pos.row = mazes[mazeNo].ghostPos.row;
g.pos.column = mazes[mazeNo].ghostPos.column;
g.edibleCountDown = 0;
}
g.edibleCountDown--;
} else {
if (touching(g.pos, packman.pos)) {
dead = true;
}
}
}
// level is cleared
if (pills.isEmpty() && powerPills.isEmpty()) {
mazeNo++;
if (mazeNo < 4) {
setMaze(mazeNo);
} else if (mazeNo == 5) {
win = true;
} else {
// game over
dead = true;
}
}
}
private boolean touching(Position a, Position b) {
return Math.abs(a.row-b.row) + Math.abs(a.column-b.column) < 3;
}
public void moveGhosts(int[] reqDirs) {
for (int i=0; i<4; i++) {
GhostInfo info = ghostInfos[i];
info.reqDir = reqDirs[i];
if (move(info.reqDir, info)) {
info.curDir = info.reqDir;
} else {
move(info.curDir, info);
}
}
}
public int getWidth() {
return mazes[mazeNo].width;
}
public int getHeight() {
return mazes[mazeNo].height;
}
public List<Integer> getPossibleDirs(Position pos) {
List<Integer> list = new ArrayList<>();
for (int d=0; d<4;d++) {
Position npos = getNextPositionInDir(pos, d);
if (mazes[mazeNo].charAt(npos.row, npos.column) != '0') {
list.add(d);
}
}
return list;
}
private Position getNextPositionInDir(Position pos, int d) {
int nrow = wrap(pos.row, MoverInfo.DROW[d], mazes[mazeNo].rows);
int ncol = wrap(pos.column, MoverInfo.DCOL[d], mazes[mazeNo].columns);
return new Position(nrow, ncol);
}
}

Categories

Resources