I am trying to sort an array of created objects each time an object is added. I wrote a compareTo method, and it is printing out each line, but throws an exception when I try to sort it. I am initializing an Element[] of 99 elements(maxLen), then using topIndex as a counter to find the "real" length. A scanner is used to get user input to create the Element. EDIT-- I added the full code.
import java.util.Arrays;
import java.util.Scanner;
public class mainmenu {
static Element[] data = new Element[100];
static int maxLen= 99;
static int topIndex= -1;
#SuppressWarnings("rawtypes")
public static void main(String[] args){
menu();
}
public static void menu(){
boolean leave = true;
Scanner in = new Scanner(System.in);
while(leave){
//loop. unless value is 1-7, keeps recycling
System.out.println("Please select a menu option: ");
System.out.println("'1'- enque ");
System.out.println("'2'- deque");
System.out.println("'3'- peek");
System.out.println("'4'- display");
System.out.println("'5' empty queue");
System.out.println("'6'- check if the queue is empty");
System.out.println("'7' to exit the program");
String select = in.next();
if ((select.equals("1") || select.equals("2")|| select.equals("3")|| select.equals("4")||
select.equals("5")|| select.equals("6")|| select.equals("7")))
leave = callMethods(select );
else{
System.out.println("Please enter a valid menu option.");
}
}
}
public static boolean callMethods(String select )
{
boolean leave= true;
int sel = Integer.parseInt(select);
switch(sel){
case 1:
enqueue();
break;
case 2:
dequeue();
break;
case 3:
peek();
break;
case 4:
display();
break;
case 5:
empty();
break;
case 6:
if( isEmpty()){
System.out.println("The structure is empty");
}
else{
System.out.println("The structure is not empty.");
}
break;
case 7:
System.out.println("Bye!");
leave = false;
}
return leave;
}
public static void enqueue(){
boolean isInt = false;
String st = null;
int index = 0;
Scanner in = new Scanner(System.in);
while(!isInt){ //loop continues until input is an integer type
System.out.println("Please enter a priority level for this element");
st = in.next();
if (isInteger(st) == true){// calls method to check if value is integer
index = Integer.parseInt(st);//parses the string into a integer
isInt = true;
}
else //if value isnt integer, try again
System.out.println("Invalid Input.");
}
System.out.println("Please enter the string of information.");
String info = in.next();
Element e = new Element(info, index);
if (topIndex == maxLen){
System.out.println("Data Structure is full.");
}
else if (isEmpty()){
data[0] = e;
topIndex++;
}
else {
topIndex++;
data[topIndex]=e;
System.out.println("Added "+ e.getPriority() + " at "+ e.getInfo());
System.out.println(topIndex);
Arrays.sort(data);
}
}
private static boolean isInteger(String s) {
//checks to see if string can be parsed as an integer.
try{
Integer.parseInt(s);
return true;
}
catch( Exception e ){
return false;
}
}
public static void dequeue(){
if(isEmpty()){
System.out.println("The structure is empty.");
}
else{
Element e = data[topIndex];
System.out.println("Removing Element: " + e.getInfo()+ " Priority Level: " + e.getPriority());
--topIndex;
}
}
public static void peek(){
if (isEmpty()){
System.out.println("The structure is empty.");
}
else {
Element e = (data[0]);
System.out.println("Element: " + e.getInfo()+ " Priority Level: " + e.getPriority());
}
}
public static void display(){
System.out.println("topIndex " + topIndex);
if (topIndex==-1){
System.out.println("The structure is empty.");
}
else {
for(int i = 0; i <= topIndex; i++){
System.out.println("Index: " +i);
Element e = data[i];
System.out.println("Element: " + e.getInfo()+ " Priority Level: " + e.getPriority());
}
}
}
public static void empty(){
System.out.println("Erasing data.");
topIndex=-1;
}
public static boolean isEmpty(){
return (topIndex==-1);
}
}
And the Element class:
public class Element implements Comparable<Element> {
private String info;
private int index;
public Element ( String st, int ind) {
super();
this.info = st;
this.index= ind;
}
public String getInfo() {
return info;
}
public void setInfo(String st) {
this.info = st;
}
public int getPriority(){
return index;
}
public void setPriority(int pr){
this.index = pr;
}
public int compareTo(Element e) {
System.out.println(e.index+ ""+ e.info);
// if (!(e instanceof Element))
// throw new ClassCastException("An Element object expected.");
int ePriority = e.getPriority();
System.out.println(ePriority);
System.out.println(this.index);
int balls= this.index - ePriority;
System.out.println(balls);
return balls;
}
}
Arrays.sort requires all of the array elements to be non-null. You want to sort only the non-null part, so replace Array.sort(data) with Arrays.sort(data, 0, topIndex + 1).
Arrays.sort(Object[], int, int)
Do not modify compareTo to allow a null argument as others have suggested, because the contract of Comparable dictates that your implementation should throw NullPointerException.
Comparable.compareTo(T)
You have given Element[] array data to Array.sort() method which has size 100, but all of the element of data array are not initialized. Hence a call such as e.getPriority(); will result in NullPointerException as e is null. Initialize all of the element of data array first.
for(int i=0 ; i< data.length; i++)
e = new Element(info, index); // replace with relevant info and index of your contest
Use Arrays.sort(Object[] array, int fromIndexInclusive, int toIndexExclusive) to sort parts of an array if needed:
Arrays.sort(data, 0, topIndex+1);
From your error description I would guess the Element object is getting null.
As per your comment
It will throw the Element object expected exception I wrote in. If I comment out the throw declaration in the compareTo method, I get a null pointer exception.
if (!(e instanceof Element))
throw new ClassCastException("An Element object expected.");
The above statement will throw the exception only the object e is NULL
When doing a comparison, you're deciding if one object outranks another by some arbitrary condition.
I notice that you don't check if the object you're comparing against is null - you should do that.
public int compareTo(Element e) {
if(e == null) {
return this.index;
} else {
// rest of your logic goes here
}
}
Related
I've looked up examples as to how Comparable works and I somewhat understand how it would work but I don't know how I would use it in this situation.
I have an ArrayObject class implements Comparable and imported java.util.*; I also have an ArrayObjectDriver class that is a main method that calls upon methods I've coded in the ArrayObject class. One of the methods that it has to be able to do is to sort the array of objects in the main method. I know you have to use something with .compareTo but I'm not sure how I would do that in the ArrayObject class and call on it in the driver.
EDIT: ArrayObject code
public class ArrayObject implements Comparable
{
private Object[] arr;
private int actualSize;
ArrayObject()
{
arr = new Object[10];
actualSize = 0;
}
ArrayObject(int size)
{
arr = new Object[size];
actualSize = 0;
}
public void add(Object obj)
{
if(actualSize>=arr.length)
expandArray();
arr[actualSize]=obj;
actualSize++;
}
public void expandArray()
{
int newSize = arr.length*2;
Object[] biggerList = new Object[newSize];
for(int i=0; i<arr.length; i++)
{
biggerList[i] = arr[i];
}
arr = biggerList;
}
public void add(Object obj, int index)
{
if(index<actualSize)
{
shiftRight(index);
arr[index]=obj;
actualSize++;
}
// index is between [0 and actualSize)
}
private void shiftRight(int start)
{
for(int i=actualSize; i>start; i--)
{
arr[i] = arr[i-1];
}
arr[start]=null;
}
private void shiftLeft(int start)
{
for(int i=start; i<actualSize-1; i++)
{
arr[i] = arr[i+1];
}
arr[actualSize-1]=null;
}
public Object remove(int index)
{ // returning the object you are removing
// ("the", "is", "are")
if(index>=0&&index<actualSize)
{
Object obj = arr[index];
arr[index] = null;
// arr[index] = arr[actualSize-1];
// what to do about the null?
// Shift to the left by one
shiftLeft(index);
actualSize--;
// ("the", null, "are")
return obj;
}
return null;
}
public Object get(int index)
{
if(index>=0&&index<actualSize)
return arr[index];
return null;
}
public int sizeOfContainer()
{
return arr.length;
}
public int items()
{
return actualSize;
}
public boolean searchArray(Object obj)
{
for(int i=0; i<actualSize; i++)
{
if(arr[i].equals(obj))
return true;
}
return false;
}
public int findObject(Object obj)
{
if(searchArray(obj))
{
for(int i=0; i<actualSize; i++)
{
if(arr[i].equals(obj))
return i;
}
}
return -1;
}
public boolean isItEmpty()
{
if(actualSize == 0)
return true;
return false;
}
public int removeSearch(Object obj)
{
for(int i=0; i<actualSize; i++)
{
if(arr[i].equals(obj))
{
remove(i);
return i;
}
}
return -1;
}
public void clearArray()
{
for(int i=0; i<actualSize; i++)
arr[i] = remove(i);
}
public void printArr()
{
System.out.println("Array Size: " + actualSize);
for(int i=0; i<actualSize; i++)
{
System.out.println(arr[i]);
}
}
}
ArrayObjectDriver code
public class ArrayObjectDriver
{
private static Scanner scanner;
public static void main(String[] args)
{
scanner = new Scanner(System.in);
ArrayObject array = new ArrayObject();
int selection = selectionMenu();
while(selection > 0)
{
if(selection == 1)
{
System.out.println("Enter your object: ");
String str = scanner.next();
array.add(str);
}
else if(selection == 2)
{
System.out.println("Enter your object: ");
String str = scanner.next();
System.out.println("Enter location: ");
int n = scanner.nextInt();
array.add(str, n);
}
else if(selection == 3)
{
System.out.println("Enter location: ");
int n1 = scanner.nextInt();
array.remove(n1);
}
else if(selection == 4)
{
System.out.println("Enter object: ");
String str = scanner.next();
int i = array.removeSearch(str);
System.out.println("Object removed at index " + i);
}
else if(selection == 5)
{
array.clearArray();
System.out.println("Cleared Array");
}
else if(selection == 6)
{
System.out.println("Enter object: ");
String str = scanner.next();
boolean result = array.searchArray(str);
System.out.println("The object was found: " + result);
}
else if(selection == 7)
{
boolean result = array.isItEmpty();
System.out.println("It is empty: + result);
}
else if(selection == 8)
{
array.expandArray();
int i = array.sizeOfContainer();
System.out.println("The new size of the array is: " + i);
}
else if(selection == 9)
{
System.out.println("Enter object: ")
String str = scanner.next();
int i = array.findObject(str);
System.out.println("The object was found at index " + i);
}
else if(selection == 10)
array.printArr();
else if(selection == 11)
{
}
else if(selection == 12)
System.exit(0);
System.out.println("");
selection = selectionMenu();
}
}
private static int selectionMenu()
{
System.out.println("Menu: ");
System.out.println("1. Add object to the end of the list");
System.out.println("2. Add object at a specific location");
System.out.println("3. Remove specific object at a location");
System.out.println("4. Remove specific object that matches name");
System.out.println("5. Empty the array");
System.out.println("6. See if the array contains a certain object");
System.out.println("7. See if the array is empty");
System.out.println("8. Expand your array");
System.out.println("9. Search for an item");
System.out.println("10. Print array");
System.out.println("11. Sort array");
System.out.println("12. Exit");
System.out.println("Enter option: ");
int optionNumber = scanner.nextInt();
return optionNumber;
}
}
Just make a sort method in your ArrayObject class and you can call that when user enters 11.
In ArraysObject:
public void sort(){
Arrays.sort(arr); //This is all you have to call to sort your array arr
}
In your ArrayObjectDriver:
else if(selection == 11)
{
array.sort();
}
The Arrays class has useful methods for searching, manipulating, and sorting arrays including Arrays.sort and Arrays.binarySearch.
I'm having a problem calling a method and then trapping its return.
I need it to update the result so the next time round the loop it will see it and return a different message.
public class Patient {
private char patientStatus;
public boolean admit() {
if (patientStatus != 'S')
return false;
else
patientStatus = 'A';
return true;
}
This section is in the main() method
do {
Patient temp = null;
System.out.print("Enter selection: ");
menuSelect = sc.nextLine();
// validation
if (menuSelect.length() != 1) {
System.out.println("You must enter a single character");
} else {
menuAnswer = menuSelect.charAt(0);
switch (menuAnswer) {
case 'A':
case 'a':
// patient number
System.out.print("Enter patient number: ");
patNumber = sc.nextLine();
// search for patient number
for (int i = 0; i < pat.length && temp == null; i++) {
if (pat[i].getPatientNo().equals(patNumber)) {
temp = pat[i];
}
}
if (temp == null) {
System.out.println("Patient not found");
} else {
System.out.println("Patient " + patNumber + " Found");
boolean patStatus = temp.admit();
if (patStatus == false) {
System.out.println("Admitted");
} else if (patStatus == true) {
System.out.println("Already admitted");
}
}
}
}
} while (menuAnswer != 'x' && menuAnswer != 'X');
System.out.println("Exiting menu");
I don't know how to update the patStatus so the next time in the menu if you select 'A' and the same patient number it returns "Already admitted".
Let me know if there's enough code to understand what's happening.
Your Patient has the atribute for patientStatus but its value is never saved. Your admit() method needs to set the value for it.
Currently, your code only returns the value but does not save it.
Try this:
public class Patient {
private char patientStatus;
/** "Getter" method for patientStatus
*/
public char getPatientStatus(){
return patientStatus;
}
/** "Admits" the new patient, changing its patientStatus
* #return "true" if patient is admitted; "false" if patient was already admitted.
*/
public boolean admit() {
if (patientStatus != 'A')
patientStatus = 'A'; //set the value to Admitted
return true;
else
return false;
}
}
Then, in your loop, test the value for the admit() call:
if (temp == null) {
System.out.println("Patient not found");
} else {
System.out.println("Patient " + patNumber + " Found");
boolean admitted = temp.admit(); // try to admit the patient
if (admitted) {
System.out.println("Admitted");
} else { //You don't need another if here
System.out.println("Already admitted");
}
}
Since admitted is of type boolean, you don't need to use the == operator, as the if statement uses a boolean value as argument.
You don't need a second if statement after the else either, since boolean can only have two values, if it is not true, then it can only be false
/* You have to re-factor the code on these lines.
Maintain Patients class which holds admitted patients.*/
public class Patients{
private ConcurrentHashMap<Integer, Patient> allPatients = new ConcurrentHashMap();
private HashSet<Integer) admittedPatients = new HashSet();
public Patients(){
}
public void add(Patient p){
allPatients.put(p.getPatientId(),p);
}
public Patient removePatient(int patientId){
dischargePatients.remove(patientId);
return allPatients.remove(patientId);
}
public Patient getPatient(int patientId){
return allPatients.get(patientId);
}
public void admitPatient(int patientId){
admittedPatients.add(patientId);
}
public boolean dischargePatient(int patientId){
return admittedPatients.remove(patientId);
}
public boolean isAdmittedPatient(int patientId){
return admittedPatients.contains(patentId);
}
}
From `Patient.java` class, you can admit & discharge patient.
If getPatient() is null implies patient is not present in list.
Once he is present, isAdmittedPatient returns whether
he is admitted or not.
I keep getting the following error message in my method:
"Error: 'void' type not allowed here" on the line outEquation = outEquation + opSt.pop() + " ";.
The code I'm working on currently is a stacked linked list which takes in user input (in infix notation) and converts it to postfix. Any help would be appreciated.
import java.util.Scanner;
public class StackDemo
{
public static void main(String[] args)
{
final int right = 0;
final int left = 1;
final int ADD = 0;
final int MULT = 1;
final int EXP = 2;
final int PAR = -1;
}
public void UserPrompt()
{
Scanner keyboard = new Scanner(System.in);
String input = keyboard.nextLine();
System.out.println("Please select what type of conversion you would like to do: ");
System.out.println();
System.out.println("1) Infix to postfix \n2) Postfix to infix \n3) Print Equations \n4) Exit");
if(input == "1")
{
infix();
}
else if(input == "2")
{
postfix();
}
else if(input == "3")
{
print();
}
else if(input == "4")
{
System.exit(0);
}
else
{
System.out.println("That is not a correct input, please re-enter.");
UserPrompt();
}
}
public String infix()
{
String outEquation = "";
LinkedStackClass<String> opSt = new LinkedStackClass<String>();
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the infix equation: ");
while(keyboard.hasNext())
{
String str = keyboard.next();
if(!isOperator(str))
{
outEquation = outEquation + str + " ";
}
else if(str.equals("("))
{
opSt.push(str);
}
else if(str.equals(")"))
{
while(!opSt.peek().equals("("))
{
outEquation = outEquation + opSt.pop() + " ";
}
opSt.pop();
}
else
{
while(opSt.size() > 0 && precede(opSt.peek(), str))
{
if(!opSt.peek().equals("("))
{
outEquation = outEquation + opSt.pop() + " ";
}
else
{
opSt.pop();
}
}
if(!str.equals(")"))
{
opSt.push(str);
}
}
while(opSt.size() > 0)
{
outEquation = outEquation + opSt.pop() + " ";
}
}
}
private static int getExpOrder(String op)
{
switch(op)
{
case "+":
case "-":
case "*":
case "/":
return left;
case "^":
return right;
//default
}
}
private boolean precede(String l, String r)
{
return (getPrec(l) > getPrec(r) || (getPrec(l) == getPrec(r) && getExpOrder(l) == left));
}
private int getPrec(String op)
{
switch(op)
{
case "+":
case "-":
return ADD;
case "*":
case "/":
return MULT;
case "^":
return EXP;
case "(":
case ")":
return PAR;
}
}
public static boolean isOperator(String op)
{
return (op.length() == 1 && "+-*/()".indexOf(op.charAt(0)) != -1);
}
public String toString()
{
return outEquation;
}
public void postfix()
{
System.out.println("Postfix");
}
public void print()
{
System.out.println("Print");
}
}
public class LinkedStackClass<T> extends UnorderedLinkedList<T>
{
public LinkedStackClass()
{
super();
}
public void initializeStack()
{
initializeList();
}
public boolean isEmptyStack()
{
return isEmptyList();
}
public boolean isFullStack()
{
return false;
}
public void push(T newElement)
{
insertFirst(newElement);
} //end push
public T peek() throws StackUnderflowException
{
if (first == null)
throw new StackUnderflowException();
return front();
} //end peek
public void pop()throws StackUnderflowException
{
if (first == null)
throw new StackUnderflowException();
first = first.link;
count--;
if (first == null)
last = null;
}//end pop
}
Ok, so the reason are you getting that error message is because your pop() function has a void return. Typically, in a stack implementation, the pop operation will remove the top item of the stack and return it. Your function only removes the element.
So change your pop() function to look as follows (I apologize in advanced, as Java is not my forté, and this may not even be correct, so you may need to tweak this):
public T pop() throws StackUnderflowException
{
if (first == null)
throw new StackUnderflowException();
// Get the top-most element
T top = peek();
first = first.link;
count--;
if (first == null)
last = null;
return top;
} //end pop
However as user Ashley Frieze stated, better to use an existing implementation if possible, rather than roll your own.
I am just curious, i have a class that implements a queue and it currently has one item... I am curious as to where would be the most efficient or cleanest location to initialize other items that i wish to add to the queue... This is part of an assignment so please provide an explanation and not just answer! thanks in advance... Here is the class i built...
import java.util.*;
public class Queue<T> extends Node<T> {
private LinkedList<T> list;
// Queue constructor
public Queue() {
// Create a new LinkedList.
list = new LinkedList<T>();
}
//check if empty
public boolean isEmpty() {
return (list.size() == 0);
}
//add items to queue
public void enqueue(Object item) {
// Append the item to the end of our linked list.
list.add((T) item);
}
//remove items from queue
public T dequeue() {
T item = list.get(1);
list.remove(1);
// Return the item
return item;
}
//check top item
public T peek() {
return list.get(1);
}
//check size of queue
public int size() {
return list.size();
}
}
This is how you write a queue:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Queue;
import java.util.*;
/**
*
* #author Madhurlucky
*/
public class arrayQueue {
public static int[] Queue;
public static int len, front, rear, size;
public arrayQueue(int n) {
len = 0;
size = n;
front = -1;
rear = -1;
Queue = new int[size];
}
public boolean isEmpty() {
return front == -1;
}
public boolean isFull() {
return (front == 0 && rear == size - 1);
}
public int getsize() {
return len;
}
public void insert(int i) {
if (rear == -1) {
rear = front = 0;
Queue[rear] = i;
} else if (rear + 1 >= size) {
System.out.println("OverFlow Queue");
} else if (rear + 1 < size) {
Queue[++rear] = i;
}
len++;
}
public int remove() {
int x = -99;
if (front != -1) {
x = Queue[front];
if (front == rear) {
front = rear = -1;
} else if (front < rear) {
front += 1;
}
len--;
}
return x;
}
/* Function to check the front element of the queue */
public int peek() {
if (isEmpty()) {
throw new NoSuchElementException("Underflow Exception");
}
return Queue[front];
}
public void display() {
System.out.print("\nQueue = ");
if (len == 0) {
System.out.print("Empty\n");
return;
}
for (int i = front; i <= rear; i++) {
System.out.print(Queue[i] + " ");
}
System.out.println();
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Array Queue Test\n");
System.out.println("Enter Size of Integer Queue ");
int n = scan.nextInt();
/* creating object of class arrayQueue */
arrayQueue q = new arrayQueue(n);
/* Perform Queue Operations */
char ch;
do {
System.out.println("\nQueue Operations");
System.out.println("1. insert");
System.out.println("2. remove");
System.out.println("3. peek");
System.out.println("4. check empty");
System.out.println("5. check full");
System.out.println("6. size");
int choice = scan.nextInt();
switch (choice) {
case 1:
System.out.println("Enter integer element to insert");
try {
q.insert(scan.nextInt());
} catch (Exception e) {
System.out.println("Error : " + e.getMessage());
}
break;
case 2:
try {
System.out.println("Removed Element = " + q.remove());
} catch (Exception e) {
System.out.println("Error : " + e.getMessage());
}
break;
case 3:
try {
System.out.println("Peek Element = " + q.peek());
} catch (Exception e) {
System.out.println("Error : " + e.getMessage());
}
break;
case 4:
System.out.println("Empty status = " + q.isEmpty());
break;
case 5:
System.out.println("Full status = " + q.isFull());
break;
case 6:
System.out.println("Size = " + q.getsize());
break;
default:
System.out.println("Wrong Entry \n ");
break;
}
/* display Queue */
q.display();
System.out.println("\nDo you want to continue (Type y or n) \n");
ch = scan.next().charAt(0);
} while (ch == 'Y' || ch == 'y');
}
}
First off, the code is long, but I am only concerned about the toString method. I pasted everything in case its relevant.
The code is supposed to check whether or not the element entered is less than the element at the top of the stack. I have that part figured out. When I call my toString method to print the saved input, it doesn't print the first node added to the stack. However, it prints all remaining inputs. A example would be if a user enters the following:
testing
test
te
t
What its currently outputing:
t te test
What it needs to output:
t te test testing
Main:
import java.util.*;
public class Stack {
public static void main(String args[]) {
int loopInt = 1;
PyramidStack<String> stringStack = new PyramidStack<String>();
PyramidStack<Integer> intStack = new PyramidStack<Integer>();
System.out
.println("This program will save some of the strings you enter. ");
System.out
.println("Can you predict which ones will be saved? (Enter nothing to quit.)");
Scanner sc = new Scanner(System.in); // Opens Scanner for keyboard input
try {
do {
System.out.print("Enter a String: ");
String input = sc.nextLine();
if (input.length() > 0) {
if (stringStack.size() == 0) {
intStack.push(input.length());
stringStack.push(input);
System.out.println("String Saved");
}
else if (input.length() < intStack.peek()) {
stringStack.push(input);
intStack.push(input.length());
System.out.println("String Saved");
}
else {
System.out.println("String NOT saved. Already saved "
+ intStack.countBefore(input.length())
+ " strings that should come before this one.");
}
} else {
System.out.println();
System.out.println(stringStack.toString());
System.out.println(intStack.toString());
loopInt--;
sc.close();
}
} while (loopInt > 0);
} catch (NullPointerException e) {
System.out.println("No strings have been entered. Ending the program.");
}
}
}
PyramidStack Method:
import java.util.*;
import java.lang.Comparable;
public class PyramidStack<E extends Comparable<E>> extends Stack<E> {
#Override
public void push(E item) throws IllegalArgumentException {
if (super.size == 0) {
super.push(item);
}
else if(item.compareTo(super.peek()) <= 0) {
super.push(item);
}
else {
System.out.println("String NOT saved. " + countBefore(item) + " strings that should come before this one.");
}
}
#Override
public String toString() {
Node<E> node;
node = this.top;
String s = "";
while(node.getNext() != null){
s += node.getData() + " ";
node = node.getNext();
}
return s;
}
public int countBefore(E item) {
Node<E> node;
node = this.top;
int i = 0;
while(node.getNext() != null){
if(item.compareTo(super.peek()) <= 0) {
node = node.getNext();
}
else{
i++;
node = node.getNext();
}
}
return i;
}
}
Stack method and Node Method below in comments.
while(node.getNext() != null){
s += node.getData() + " ";
node = node.getNext();
}
This is where you are missing to print the last data.. you are checking node.getnext() is null.. so it skips the last object and doesn't print that.. your condition should be
node != null
OR
After the loop end have this
s += node.getData() -- this will not give null pointer exception as node is not null.. as it did check node.getnext()
Hope it helps