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.
Related
Full Disclosure: This was an assignment, it has been marked already, but I want to understand why I'm getting this error.
I'm having some issues understanding why junit.framework.AssertionFailedError is being thrown. Normally when errors occur I could at least look at the stack trace and see what is happening. In this case, the output console shows this:
Testcase: testIsCorrectMCQ(mr_3.myTester): FAILED
null
junit.framework.AssertionFailedError
at mr_3.MyTester.testIsCorrectMCQ(Assign03Tester.java:207)
testIsCorrectMCQ(mr_3.MyTester): FAILED
In the test result tab in NetBeans, copying the stack trace gives me:
junit.framework.AssertionFailedError
at mr_3.myTester.testIsCorrectMCQ(myTester.java:207)
In the tester file, I have this:
#Test
public void testIsCorrectMCQ() {
System.out.println("isCorrect of MCQ");
MCQuestion instance = new MCQuestion(1,"Capital city of Canada is", 'A',
"Ottawa", "Vancouver", "New York", "Toronto");
assertFalse(instance.isCorrect("B"));
assertTrue(instance.isCorrect("A")); // line 207
}
My isCorrect method is this:
#Override
public boolean isCorrect(Object guess) {
if (guess == null)
return false;
if (guess instanceof String) {
String userGuess = (String)guess;
return (userGuess.charAt(0) == this.getAnswer());
}
if (guess instanceof Character) {
Character userGuess = (Character)guess;
return (userGuess == this.getAnswer());
}
else return false;
}
Any help in understanding what is happening is greatly appreciated.
Edit 1 : My MCQuestion source code
public class MCQuestion extends Question {
private char answer;
private String[] options;
public MCQuestion() {
super();
questionType = QuestionType.MULTIPLE_CHOICE;
}
public MCQuestion(int id, String text, char answer, String... options) {
super(id, text);
setOptions(options);
setAnswer(answer);
questionType = QuestionType.MULTIPLE_CHOICE;
}
public String[] getOptions() {
String[] getOptions = new String[this.options.length];
System.arraycopy(this.options, 0, getOptions, 0, this.options.length);
return getOptions;
}
public void setOptions(String... options) {
if (options.length > 0) {
this.options = new String[options.length];
for (int i = 0; i < options.length; i++) {
if (options[i].isEmpty())
throw new IllegalArgumentException("You have nothing in this option");
else
this.options[i] = options[i];
}
}
else throw new IllegalArgumentException("You have no options set");
}
public char getAnswer() {
return this.answer;
}
public void setAnswer(char ans) {
ans = Character.toLowerCase(ans);
int index = ans - 97;
if (Character.isLetter(ans) && index >= 0 && index < this.options.length)
this.answer = ans;
else throw new IllegalArgumentException(ans + " is not a valid answer option");
}
#Override
public boolean isCorrect(Object guess) {
if (guess == null)
return false;
if (guess instanceof String) {
String userGuess = (String)guess;
return (userGuess.charAt(0) == this.getAnswer());
}
if (guess instanceof Character) {
Character userGuess = (Character)guess;
return (userGuess == this.getAnswer());
}
else return false;
}
#Override
public String toString() {
String option = "";
if (this.options.length == 0)
option = "No options added, yet!";
else {
char index = 'a';
for (String e: options)
option += index + ") " + e + "\n";
}
return (super.toString() + "\n" + option);
}
}
You execute ans = Character.toLowerCase(ans); for whatever reason in your setAnswer() method before saving it in this.answer. This means that (userGuess.charAt(0) == this.getAnswer()) will return false when you provide the answer in upper case, but compare it with the stored lower case character.
Depending on if you want case insensitive answers or not, you should add or remove the Character.toLowerCase() call to your isCorrect() method as well.
i got two different kind of errors in my code.
one is when someone enters a number that's higher than 8 or lower than 0.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 22
at boter_kaas_en_eiren.Board.placeAttempt(Board.java:37)
at boter_kaas_en_eiren.Game.play(Game.java:28)
at boter_kaas_en_eiren.MainClass.main(MainClass.java:12)
the other error is when a player wins and i want to close the scanner so nobody can play anymore.
Exception in thread "main" java.lang.IllegalStateException: Scanner closed
at java.util.Scanner.ensureOpen(Unknown Source)
at java.util.Scanner.findWithinHorizon(Unknown Source)
at java.util.Scanner.nextLine(Unknown Source)
at boter_kaas_en_eiren.Game.play(Game.java:23)
at boter_kaas_en_eiren.MainClass.main(MainClass.java:12)
if somebody could help me i would appriciate it.
game class
package boter_kaas_en_eiren;
import java.util.Scanner;
public class Game {
private Board board;
private boolean gameFinished;
public Game() {
board = new Board();
gameFinished = false;
}
public void play() {
Scanner scan = new Scanner(System.in);
int x = 0;
String nextSymbol = "x";
board.ShowBoard();
while (gameFinished == false) {
String input = scan.nextLine();
int position = Integer.parseInt(input);
boolean highorlow = board.tohighorlow(position);
boolean succes = board.placeAttempt(position, nextSymbol);
if (highorlow) {
if (succes) {
if (nextSymbol.equals("x")) {
nextSymbol = "o";
} else {
nextSymbol = "x";
}
}
}
board.ShowBoard();
if (board.checkWinner("x") == true) {
System.out.println("x wins");
scan.close();
}
if (board.checkWinner("o") == true) {
System.out.println("x wins");
scan.close();
}
}
}
}
main class
package boter_kaas_en_eiren;
public class MainClass {
public static void main(String[] args) {
Game game = new Game();
game.play();
}
}
board class
package boter_kaas_en_eiren;
import java.util.Scanner;
public class Board {
private String[] board;
public Board() {
board = new String[9];
for (int i = 0; i < board.length; i++) {
board[i] = " ";
}
}
public void ShowBoard() {
System.out.println(board[0] + "|" + board[1] + "|" + board[2]);
System.out.println(board[3] + "|" + board[4] + "|" + board[5]);
System.out.println(board[6] + "|" + board[7] + "|" + board[8]);
System.out.println("");
}
public boolean tohighorlow(int position) {
if (position <= 8 && position >= 0) {
return true;
} else {
System.out.println("Invalid!!");
return false;
}
}
public boolean placeAttempt(int position, String symbol) {
if (board[position].equals(" ")) {
board[position] = symbol;
return true;
} else {
System.out.println("invalid!");
return false;
}
}
public boolean checkWinner(String symbol) {
if (board[0].equals(symbol) && board[1].equals(symbol) && board[2].equals(symbol)) {
return true;
} else if (board[3].equals(symbol) && board[4].equals(symbol) && board[5].equals(symbol)) {
return true;
} else if (board[6].equals(symbol) && board[7].equals(symbol) && board[8].equals(symbol)) {
return true;
} else if (board[0].equals(symbol) && board[3].equals(symbol) && board[6].equals(symbol)) {
return true;
} else if (board[1].equals(symbol) && board[4].equals(symbol) && board[7].equals(symbol)) {
return true;
} else if (board[2].equals(symbol) && board[5].equals(symbol) && board[8].equals(symbol)) {
return true;
} else if (board[0].equals(symbol) && board[4].equals(symbol) && board[8].equals(symbol)) {
return true;
} else if (board[2].equals(symbol) && board[4].equals(symbol) && board[6].equals(symbol)) {
return true;
} else {
return false;
}
}
}
If you would thoroughly check the source code lines given in the exceptions, you could probably find the issues yourself. But let's go through it together this time:
ArrayIndexOutOfBoundsException
This means you are trying to access an array element that is simply not there.
In your Game class, you have these two lines:
boolean highorlow = board.tohighorlow(position);
boolean succes = board.placeAttempt(position, nextSymbol);
Looking at tohighorlow(), we find this line:
if (position <= 8 && position >= 0) {
return true;
}
However, this will return true if the number is in the range [0..8]. In other words, the method returns true when your number is neither too high nor too low. Easiest fix is to change the condition like this:
if (position > 8 || position < 0)
Now numbers greater than 8 or lower than 0 will yield true, which seems to be what the method is supposed to do. Alternatively, you could swap the bodies of the if and else.
Regardless of that, you are ignoring the result of this method when you call placeAttempt() in your Game class. That's not good, because looking at placeAttempt() we find this line:
if (board[position].equals(" ")) { /* ... */
This is where your exception originates. You are accessing the board array without checking the position value. Or rather, you did check the position value but did not respect the result of that check here. Hence, if position is -2 or 12, for example, you will run into trouble as those elements do not exist (are out of bounds).
IllegalStateException: Scanner closed
Let's simplify the play() method of your Game class for a second:
public void play() {
Scanner scan = new Scanner(System.in);
/* ... */
while (gameFinished == false) {
String input = scan.nextLine();
/* ... */
boolean highorlow = board.tohighorlow(position);
boolean succes = board.placeAttempt(position, nextSymbol);
/* ... */
if (board.checkWinner("x") == true) {
System.out.println("x wins");
scan.close();
}
if (board.checkWinner("o") == true) {
System.out.println("x wins");
scan.close();
}
}
}
The first thing you do is to create the Scanner. Now, under certain circumstances (the two if at the end), you close the scanner. However, you do that within a loop. After you close the scanner, the loops starts over with its first line:
String input = scan.nextLine();
But you can't get the next line of a closed scanner.
Additional notes
I noticed that you are quite inconsistent in your style. For example, see these three method names: ShowBoard, placeAttempt and tohighorlow. You use different capitalization for each. I strongly suggest to stick to the recommended naming convention, which means camelCase with lower first letter: showBoard, placeAttempt and tooHighOrLow (also notice to vs too).
Hope this helps.
Your array board has the size 9. So if someone enters a number not between 0 and 8 you get an Exception.
You pass the input from the user directly to your function:
board.placeAttempt(position, nextSymbol);
There you do:
if (board[position].equals(" ")) {
So you try to access an invalid position of the array
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 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
}
}
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