linkedlist has two sizes - java

I'm trying to add to a LinkedList values from the accelerometer.
private LinkedList<Float> rawValues = new LinkedList<Float>();
public void onSensorChanged(SensorEvent event)
{
int eventType = event.sensor.getType();
switch(eventType)
{
case Sensor.TYPE_ACCELEROMETER:
float accelerometer_z = event.values[2];
rawValues.add(accelerometer_z);
/**
* This printout gives me positions and event values
*/
System.out.println("getAccelerometer size: " +
rawValues.size() + " entry: " + rawValues.getLast());
break;
}
}
So far so good, I get readings and number positions as expected.
However, when I'm trying to do stuff with the list in other methods, it appears to be empty!
public String[] getVelocity()
{
String[] velocityString = {"42","42"};
String values = "";
String theInteger = "";
/**
* Returns a 0 size...
*/
int theSize = rawValues.size();
System.out.println("getVelocity size: " + theSize);
LinkedList<Float> slopeValues = calculateSlopeValues( rawValues);
for (int i = 0; i < theSize; i++)
{
values += "Raw:"+i+ " " + String.valueOf(rawValues.get(i)) + "\n";
values += "\tSlope:"+i+ " " + String.valueOf(slopeValues.get(i)) + "\n";
}
theInteger = String.valueOf(Math.round(Collections.max(slopeValues)*100));
/**
* After adding everything to local variables, the list is cleared.
*/
slopeValues.clear();
velocityString[0] = theInteger;
velocityString[1] = values;
return velocityString;
}
getVelocity method is called from the onTouch in the main activity.
Shed some light, please?
Regards
/M
Overridden onTouch method:
#Override
public boolean onTouch(View view, MotionEvent event)
{
MySensorEventListener eventListener = new MySensorEventListener();
switch(event.getAction())
{
case MotionEvent.ACTION_DOWN:
String[] strings = eventListener.getVelocity();
String velocity_int = strings[0];
String velocity_string = strings[1];
velocityView.setText(velocity_int);
listView.setText(velocity_string);
break;
}
return false;
}

Well, each time onTouch() is called, you create a new instance of MySensorEventListener, and ask this new instance for its velocity. Since each MySensorEventListener instance has its own linked list of raw values, you get an empty list each time.
The listener should probably be created only once, and stored in an instance field of the enclosing class.

Related

Java array of queues printing out only last element within for loop in print method

I spent several hours working on this and even had my professor look at this and it seems to be printing out just the last element in the for loop. It seems to allows me to add the data structure information and initialize the array queue but it only print out the last element. Here is the sufficient code to assist with the question.
static int MAX;
static final int amount = 6;
static boolean [] openflag;
static queue [] Clinic;
static String [] Doctor;
final static String HEADING = "The clinic moniter of Dylan Rychlik";
public static void Listpaitents( ) {
Paitent[] array;
int queuechoice;
JOptionPane.showMessageDialog(null, "Which doctor would you like to
print?");
String InputString = JOptionPane.showInputDialog(null,Doctor, HEADING,
JOptionPane.QUESTION_MESSAGE);
queuechoice = Integer.parseInt(InputString);
if (openflag[queuechoice -1 ] == false){
JOptionPane.showMessageDialog(null, "Sorry, that doctor is not aviable");
}
else {
//Paitent[] array = null;
int limit;
limit = Clinic[queuechoice -1 ].getSize();
array = Clinic[queuechoice -1 ].toArray();
System.out.println(array[0]);
System.out.println(array[1].Print());
System.out.println(array[2].Print());
//int size = Clinic[queuechoice -1].getSize();
//System.out.println(limit);
int x; String out = " Members of the list are: \n";
// boolean exit = false;
for(x = 0; x < limit; x++) {
out += array[x].Print() + "\n";
//System.out.println(out);
// System.out.println(Clinic[queuechoice].toString() + "\n");
}
System.out.println(limit);
JOptionPane.showMessageDialog(null,out);
}
}
Here this is the array() method in the queue clas
public Paitent[] toArray() {
int x;
Paitent[] Array = new Paitent[Length];
queuenode Current = rear;
for (x = 1; ((Current != null) && (x <= Length));x++) {
Array[x-1] = new Paitent();
Array[x-1].update(Current.info);
Current = Current.next;
// System.out.println( Array[x-1].Print());
}
//System.out.println( Array[x-1].Print());
return Array;
}
Any finally here this is the print method
public String Print() {
String outputString;
outputString = "Paitent: " + "-" + name + "\n" + " Telephone number
telephone + " ID " + ID;
return outputString;
}
Any help you can give is really appreciated. I really have spent hours analyzing the code to come up a solution. Its a bulky program.

How do I configure this Java method connected to several classes that all get more specific?

All of the program's templates. This was a past assignment but at this point, I'm just trying to understand what's going on.
Under the Apartment class, I'm confused on how to correctly return an array of window orders for one unit, all units, and then the #Override method under ThreeBedroom.
Just for reference of what I've done so far (probably not all correct):
public class Window {
private final int width, height;
public Window(int width, int height) {
this.width = width;
this.height = height;
}
// print text like: 4 X 6 window
public String toString() {
String s = "";
s = width + " x " + height + " window";
return s;
}
// compare window objects by their dimensions
public boolean equals(Object that) {
if (that instanceof Window) {
Window w = (Window) that;
return this.width == w.width && this.height == w.height;
}
else { return false; }
}
}
class WindowOrder {
final Window window; // window description (its width and height)
int num; // number of windows for this order
WindowOrder(Window window, int num) {
this.window = window;
this.num = num;
}
// add the num field of the parameter to the num field of this object
//
// BUT
//
// do the merging only of two windows have the same size
// do nothing if the size does not match
//
// return the current object
WindowOrder add(WindowOrder order) {
if (order.equals(window)) {
this.num -= num;
return order;
}
else {
return order;
}
}
// update the num field of this object by multiplying it with the parameter
// and then return the current object
WindowOrder times(int number) {
WindowOrder window = new WindowOrder(this.window, this.num);
this.num *= number;
return window;
}
// print text like: 20 4 X 6 window
#Override
public String toString() {
String s = "";
s = num + " " + window.toString();
return s;
}
// Two orders are equal if they contain the same number of windows of the same size.
#Override
public boolean equals(Object that) {
if (that instanceof WindowOrder) {
WindowOrder order = (WindowOrder) that;
return this.num == order.num && this.window == order.window;
}
else { return false; }
}
}
public class Room {
Window window;
int numOfWindows;
Room(Window window, int numOfWindows) {
this.window = window;
this.numOfWindows = numOfWindows;
}
WindowOrder order() {
return new WindowOrder(window, numOfWindows);
}
// Print text like: 5 (6 X 8 window)
#Override
public String toString() {
String s = "";
s = numOfWindows + " (" + window.toString() + ")";
return s;
}
// Two rooms are equal if they contain the same number of windows of the same size
#Override
public boolean equals(Object that) {
if (that instanceof Room) {
Room room = (Room) that;
return this.window == room.window && this.numOfWindows == room.numOfWindows;
}
else { return false; }
}
}
class MasterBedroom extends Room {
MasterBedroom() {
super(new Window(4, 6), 3);
}
// Call parent's toString method
//
// return text like: Master bedroom: 3 (4 X 6 window)
#Override
public String toString() {
String s = "";
s = "Master bedroom: " + numOfWindows + " " + window.toString();
return s;
}
}
class GuestRoom extends Room {
GuestRoom() {
super(new Window(5, 6), 2);
}
// Call parent's toString method
//
// return text like: Guest room: 2 (5 X 6 window)
#Override
public String toString() {
String s = "";
s = "Guest room: " + numOfWindows + " " + window.toString();
return s;
}
}
class LivingRoom extends Room {
LivingRoom() {
super(new Window(6, 8), 5);
}
// Call parent's toString method
//
// return text like: Living room: 5 (6 X 8 window)
#Override
public String toString() {
String s = "";
s = "Living room: " + numOfWindows + " " + window.toString();
return s;
}
}
For Apartment's orderForOneUnit() method, I wrote this, but it seems to simplistic and I feel like I should be using a for loop..
WindowOrder[] orderForOneUnit() {
WindowOrder[] order = new WindowOrder[rooms.length];
return order;
}
Am I even close to correctly understanding this? What should be under the Apartment methods?
Didn't looks at the templates but from what you've provided, you're close. All you've done so far is create a WindowOrder[] array of length rooms. You need to add new WindowOrder(desc, num) to these arrays before return order;
/**
* All apartment rooms have the same number of windows, with the
* same size window for each of those.
*/
public class Apartment
{
private int numRooms_;
private int windowsPerRoom_;
private Window window_;
/**
* Constructor
*/
public Apartment(numRooms, windowsPerRoom, desiredWindowHeight, desiredWindowLength)
{
numRooms_ = numRooms;
windowsPerRoom_ = windowsPerRoom;
window_ = new Window(desiredWindowHeight, desiredWindowLenght);
}
/**
* Orders for one room in apartment
*/
public WindowOrder orderForOneUnit()
{
WindowOrder order = new WindowOrder(window_, 1);
return order;
}
/**
* Orders for all rooms in apartment
*/
public List<WindowOrder> orderForAllUnits()
{
List<WindowOrder> orders = new ArrayList<WindowOrder>();
WindowOrder order;
for(i=0; i<numRooms_; i++)
{
orders.add(new WindowOrder(window_, windowsPerRoom_);
}
return orders;
}
}
Now when you're in your code and you're ready for a new Apartment(x, x, x, x) you can do the following (I'll assume you're just in main())
public class ApartmentComplex
{
public static void main(String[] args)
{
int numWindowsPerRoom = 3;
int desiredWindowHeight = 10;
int desiredWindowWidth = 10;
int numRooms = 5;
Apartment aptWithFiveRooms = new Apartment(numRooms, numWindowsPerRoom, desiredWindowHeight, desiredWindowWidth);
WindowOrder singleSingleOrder = apt.orderForOneUnit();
List<WindowOrder> allRoomsOrder = apt.orderForAllUnits();
numRooms = 3;
Apartment aptWithThreeRooms = new Apartment(numRooms, numWindowsPerRoom, desiredWindowHeight, desiredWindowWidth);
List<WindowOrder> threeRoomsOrder = apt.orderForAllUnits();
}
}
You do need a for loop. At the moment you are returning an Array where each entry in the array is null.
Here is an example of filling an array:
for (int i = 0; i < array.length; i++) { // iterate over an array
array[i] = getValueFor(i); // put value in the array
}

removeZero() method when creating linkedlist?

I am creating a LinkedList from scratch, in the form of a train. So I have a class called Domino which creates each node, and then I have the class Train, which includes the add, size, remove etc methods. My problem is:
removeZeros() method: I cannot have any parameters, but I must delete all the nodes with zeros in them. What my program does instead is find all the zeros in the list, and delete all the nodes up until there are no more zeros. The zeros were added in a client class.
here is my Train class:
public class Train{
private Domino engine;
private Domino caboose;
private int insertS;
public Train(){
engine = null;
caboose = engine;
}
/** WHERE IM HAVING TROUBLE
* removeZero() - remove any Dominos from the train that have one or more zero spots
* while maintaining the linked list structure.
*/
// method is now just getting the spot1 0 and printing that
public void removeZero(){
Domino current = engine;
Domino hold = caboose.next;
while (current != hold) {
if(current.spot1 == 0 ||current.spot2 == 0){
current = current.next;
engine = current;
System.out.println("b " + engine);
}else{
current = current.next;
}
}
public String toString(){
String ts = "{ empty }";
if (engine == null) {
return ts;
} else {
Domino hold = engine;
ts = "{ ";
while (hold != caboose) {
ts += hold + ", ";
hold = hold.next;
}
ts += hold + " }";
}
return ts;
}
/**
*
* add(spot1, spot2) - add a Domino to the end of the Train with the given spots
*/
public void add(int spot1, int spot2){
if (engine == null) {
engine = new Domino(spot1,spot2);
caboose = engine;
} else {
caboose.next = new Domino(spot1, spot2, null,caboose);
//tail.next.back = tail;
caboose = caboose.next;
}
}
}
/**
* reversePrint() - like toString, but provides a String that lists
* all of the Dominos that are in the Train in reverse order
*/
public String reversePrint () {
Domino hold = caboose;
String reverse = "{ empty }";
if (engine == null) {
System.out.println(reverse);
} else {
reverse = "{ ";
while (hold != engine){
reverse += hold + ", ";
hold = hold.back;
}
reverse += hold + " }";
}
return reverse;
}
/**
* size() - return the number of Dominos in the Train
*/
public int size(){
int count = 0;
Domino hold = engine;
while(hold != null){
hold = hold.next;
count++;
}
return count;
}
/** insert(spot1, spot2, next, back) - insert a Domino in the middle of
* the Train where spot2 is the same as the spot1 of the next Domino and spot1
* is the same as spot2 of the previous Domino.
* (private)
*/
private void insert(int spot1,int spot2){
if (!(insertS == search)) {
Domino hold = engine;
while (hold != caboose) {
if (hold.spot1 == search) {
Domino newDom = new Domino(spot1, spot2, null,caboose);
hold.next = newDom;
newDom.next.back = newDom;
hold = hold.next;
} else {
hold = hold.next;
}
}
if (hold.spot2 == search) {
add(spot1, spot2);
}
} else {
System.out.println(" ** Error Inserting these values will cause an infinite loop:");
System.out.println(" * * * " + insertS + " and " + search + " * * *");
}
}
/**
* build() - scans through the Train creating links, using insert(spot1, spot2), between
* existing Dominos where the second spot of the first Domino does not match the
* first spot of the second domino, no param
*/
public void build(){
insert(search, insertS);
}
}
here is my Domino class:
public class Domino{
public int spot1; // the leading half how many spots it has
public int spot2; // the trailing half how many spots it has
public Domino next; // a link to the next Domino (type)?
public Domino back; // a link to the previous Domino
private int zero;
/**
* Constructor
* Creates null Domino
*
*/
public Domino(){
this(0,0 , null, null);
}
/**
* Constructor
* a constructor for Domino with given spots
*/
public Domino( int spot1, int spot2){
this(spot1,spot2, null, null);
}
/**
* Constructor
* #param: all fields
* setting variables
*/
public Domino(int spot1, int spot2, Domino next, Domino back){
this.spot1 = spot1;
this.spot2 = spot2;
this.next = next;
this.back = back;
}
/**
* toString(): prints out single Domino
*
*/
public String toString(){
if(this == null){
return("[empty]");
}else{
return("[ " + spot1 + " | "+ spot2 + "]");
}
}
}
I've really been stuck on this for the past day or so and can't seem to figure it out. Any help would be great. If you need the client code please say so. Thanks!
In the case of encountering a zero domino, you assign engine to be the current domino. As engine is the head of the list, this is equivalent to deleting all the items preceding the one containing a zero. Deletion in linked list is usually accomplished by something like:
toDelete.back.next = toDelete.next;
toDelete.next.back = toDelete.back
where toDelete is a Domino object with a zero in this case. As no domino now has a reference to the toDelete domino, it is essentially deleted.

Check if two numbers exist in two dependent arrays - Java

I have two arrays of double values called lat2[] and lon2[]. I have there stored the particular lattitude and longtitude values. And I can get those values as simple double values. My question is how can I find if this two doubles exist in the array (to check which marker has been clicked simply). Here is what I've done so far but it doesnt seem to work:
#Override
public boolean onMarkerClick(Marker marker) {
markerLatLng = marker.getPosition();
markerLat = markerLatLng.latitude;
markerLng = markerLatLng.longitude;
for (int i = 0; i < lat2.length; i++) {
if (markerLat == lon2[i]) {
for (int j = 0; j < lon2.length; j++) {
if (markerLng == lon2[j]) {
String title = marker.getTitle();
Log.e("TAG", " " + title);
}
}
}
}
return true;
}
Probably if I understood your data structure there is a problem in your for loop.
If you store latitude and longitude in two arrays I imagine that a point in position n is defined by longitude[n] and latitude[n].
If this is how you store your points here is how you need to update your code:
#Override
public boolean onMarkerClick(Marker marker) {
int markerLat = marker.getPosition().latitude;
int markerLng = marker.getPosition().longitude;
for (int i = 0; i < lat2.length; i++) {
if (markerLat == lat2[i] && markerLng == lon2[j]) {
String title = marker.getTitle();
Log.e("TAG", " " + title);
}
}
return true;
}
Please don't use global variables. I edited your code to define markerLat and markerLng local to the method (I don't know if int is the correct type).
Create a List for example ArrayList from the lat2, log2 array and check if the numbers contains like:
List lat = new ArrayList(lat2);
List lon = new ArrayList(lon2);
if (lat.contains(markerLat) && lon.contains(markerLng)){
String title = marker.getTitle();
Log.e("TAG", " " + title);
}

Java - using logical OR in do while

I'm fairly new at this programming, so please do bear with me.
In teaching myself I'm attempting to write a Batteleships game; not OO at the moment, but rather procedural - little steps at a time.
I have a method to read the coordinates to fire at, these coordinates I want to then validate to make sure that, well, they're valid.
There is one method that checks that they are numbers and within the correct range, the other method is 'supposed' to check through what has already been entered.
The issue I'm finding is that I'm not breaking out of the do while loop to progress, the while bit is using logical OR on the two aforementioned methods. In writing these methods, they both do what they're supposed to do, well I'm not entirely sure about the method that checks whether a coordinate has already been fired at.
Some pointers would be really appreciated (on any aspect of it), thanks!
Code:
public static String inputCoords(List<String> coordsFired){
Scanner sc = new Scanner(System.in);
//Console c = System.console();
String coordsEntered;
do {
System.out.println("in do\\while");
System.out.println("Enter coordinates as 'x, y': ");
coordsEntered = sc.nextLine();
System.out.println("end of do\\while loop");
} while(!validateCoords(coordsEntered)
|| !coordsFiredAt(coordsEntered, coordsFired));
coordsFired.add(coordsEntered);
System.out.println("contents of List<String> coordsFired" + coordsFired);
return coordsEntered;
}
public static boolean validateCoords(String coordsEntered){
boolean results;
int x, y;
String strx = splitCoordsString(coordsEntered, 'x');
String stry = splitCoordsString(coordsEntered, 'y');
if (numericCheckCoordsFire(strx) && numericCheckCoordsFire(stry)) {
x = Integer.parseInt(strx);
y = Integer.parseInt(stry);
if (x > 25 || y > 25) {
results = false;
System.out.println("The dimensions of the board are 25 x 25, 'x,y' entered must be less than this. You entered '" + strx + "' for x and '" + stry + "' for y.");
} else {
results = true;
}
} else {
results = false;
System.out.println("Coords are supposed to be numbers... You entered '" + strx + "' for x and '" + stry + "' for y.");
}
System.out.println(results);
return results;
}
public static boolean coordsFiredAt(String coordsEntered, List<String> coordsFired) {
boolean results = false;
// go through each item in the list and compare against coordsEntered
for (String s : coordsFired) {
System.out.println("in for loop, printing iterated var" + s);
if (s.equals(coordsEntered)) {
// put these matched coordsFire into listHit
results = false;
} else {
System.out.println("already fired at " + coordsEntered);
results = true;
}
}
return results;
}
I propose you add OOP a little and create a class for Coords:
public class Coords {
private final int x;
private final int y;
public Coords(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
/**
* This method is used for Coords comparison
*/
#Override
public boolean equals(Object o) {
Coords coords = (Coords) o;
return y == coords.y && coords.x ==x;
}
/**
* This method is used to output coords.
*/
#Override
public String toString() {
return "(" + x + "," + y + ")";
}
}
So you code will look somethink like this:
public static Coords inputCoords(List<Coords> coordsFired) {
Scanner sc = new Scanner(System.in);
//Console c = System.console();
Coords coords;
do {
System.out.println("in do\\while");
System.out.println("Enter coordinates as 'x, y': ");
String coordsEntered = sc.nextLine();
coords = parseCoords(coordsEntered);
System.out.println("end of do\\while loop");
} while (coords == null || !areCoordsValid(coords) || !areCoordsNotFired(coords, coordsFired));
coordsFired.add(coords);
System.out.println("contents of List<String> coordsFired" + coordsFired);
return coords;
}
public static boolean areCoordsValid(Coords coords) {
boolean result = true;
if (coords.getX() > 25 || coords.getY() > 25) { // I think you also need to validate that it is possible values
result = false;
System.out.println("The dimensions of the board are 25 x 25, 'x,y' entered must be less than this. " +
"You entered '" + coords.getX() + "' for x and '" + coords.getY() + "' for y.");
}
return result;
}
public static boolean areCoordsNotFired(Coords coords, List<Coords> firedCoards) {
boolean result = true;
if (firedCoards.contains(coords)) {
result = false;
System.out.println("You already fired at " + coords.getX() + "," + coords.getY());
}
return result;
}
public static Coords parseCoords(String coordsEntered) {
Coords coords = null;
try {
String[] splittedCoords = coordsEntered.split(","); // Method splits values by comma. It should return an array of Strings with x value at the first element and y at the second one;
if (splittedCoords.length == 2) {
String x = splittedCoords[0].trim(); // Method removes all spaces at the beginning and ending of a passed String
String y = splittedCoords[1].trim();
coords = new Coords(Integer.parseInt(x), Integer.parseInt(y)); //Creates new instance of Coords class. x and y are passed as constructor params.
} else {
System.out.println("Format for coords is wrong. You entered '" + coordsEntered + "'.");
}
} catch (NumberFormatException e) { // Integer.parseInt throws an exception if the string does not contain parsable integer.
// We catch an exception and handle it by writing a message
System.out.println("Coords are supposed to be numbers... You entered '" + coordsEntered + "'.");
}
return coords;
}
Also Set is more applicable in this case. Set contains no duplicate elements and Set.contains() method works faster then List.contains(). But if you want to use Set you should implement both equals() and hashCode() methods.
You want to loop if the coords are invalid or already fired.
So shouldn't the while condition be:
while(!validateCoords(coordsEntered)
|| coordsFiredAt(coordsEntered, coordsFired))

Categories