In the queue I have implemented below, the students are displayed from oldest to newest. I want to display inserted students from the newest to oldest.
The Driver code for the queue
import java.util.Scanner;
public class Driver {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("How many Students are there ? ");
int usercount = sc.nextInt();
Queue obj = new Queue(usercount);
boolean flag = true;
while(flag) {
System.out.println("Queue Operations");
System.out.println("====================");
System.out.println("1.Insert Students Name");
System.out.println("2.Remove First inserted student");
System.out.println("3.Display All Students");
System.out.println("4.Exit");
System.out.println("========================");
System.out.println("Enter Your Choice : ");
String userchice = sc.next();
if(userchice.equalsIgnoreCase("1")) {
for(int i=0; i<usercount; i++) {
System.out.println("Enter Student Name : ");
String sname = sc.next();
obj.Enqueue(sname);
}
}else if(userchice.equalsIgnoreCase("2")) {
obj.Dequeue();
}else if(userchice.equalsIgnoreCase("3")) {
obj.displayall();
}else if(userchice.equalsIgnoreCase("4")) {
System.out.println("End of Program");
flag = false;
}
}
}
}
The code for the queue
public class Queue {
int front;
int rear;
String[] username;
int size;
public Queue(int usercount) {
this.size = usercount;
this.front = 0;
this.rear = -1;
this.username = new String[usercount];
}
public Boolean isFull() {
if( this.rear == this.size - 1 ) {
return true;
}else {
return false;
}
}
public Boolean isEmpty() {
if( (this.rear == -1) || (this.rear < this.front) ) {
return true;
}else {
return false;
}
}
public void Enqueue(String item) {
if(isFull()) {
System.out.println("Queue is Full.Cannot Insert");
}else {
this.rear++;
this.username[rear] = item;
System.out.println("Element " + item + " is inserted.");
}
}
public void Dequeue() {
if(isEmpty()) {
System.out.println("Queue is Empty.Cannot Delete");
}else {
String topelem = this.username[front];
this.username[front] = "";
System.out.println("Top Element " + topelem + " is removed.");
for(int i=0; i < rear ; i++) {
this.username[i] = this.username[i+1];
}
this.username[rear] = "";
this.rear--;
}
}
public void displayall() {
for(int i=0; i < this.size ; i++) {
System.out.println("Name = " + username[i]);
}
}
}
**Let's say I entered a,b,c as students in my choice in 1.When I enter my choice as 3 (display all students) the result is
Name = a Name = b Name = c
What I WANT IS THE RESULT
Name = c Name = b Name = a
This is not a HW or assignment. This is something i'm practicing myself.I really do not know how to start.
**
Just try do a reverse for loop.
for(int i = rear;i>=0;i--) {
System.out.print(this.username[i]);
}
Related
I have been trying to use my own Linked List class (LList) to help store Dwelling objects in a RealEstate Class, which has a linked list of dwelling objects I pull from and store in an associated data file. I am having trouble implementing a menu within the RealEstate class that allows the user to interact with the linked list and as a result make changes to the associated data file. For some reason my program seems to hang on the line when I try to request user input after trying to display my menu. Any help would be greatly appreciated!
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
import java.io.FileReader;
import java.io.Console;
import java.io.DataInputStream;
public class RealEstate2
{
LList<Dwelling> dList= new LList<Dwelling>();
int ch;
FileReader w = null;
String line1=null;
String line2=null;
String line3=null;
double foot = 0;
double val = 0;
String dwellings = null;
private String fileName;
//int choice = 1;
//constructor
public RealEstate2(String m) throws FileNotFoundException, ListException
{
fileName = m;
//File data = new File(fileName);
Scanner sc = new Scanner(new File(fileName));
try
{
while (sc.hasNextLine())
{
line1 = sc.nextLine();
line2 = sc.nextLine();
line3 = sc.nextLine();
foot = Double.parseDouble(line2);
val = Double.parseDouble(line3);
dList.add(new Dwelling(line1,foot,val));
}
}
catch(ListException a)
{
throw new ListException("fuck");
}
sc.close;
//System.out.println(dList);
}//end constructor
public void Manage() throws IOException
{
Scanner in = new Scanner(System.in);
//Console console = System.console();
System.out.println("1. Display items");
System.out.println("2. Add item");
System.out.println("3. Insert item");
System.out.println("4. Delete item");
System.out.println("5. Exit");
System.out.println("Enter option:");
int choice = Integer.parseInt(System.console().readLine());
//choice = in.nextInt();
try
{
//display
if (choice == 1)
System.out.println(this);
//add
if (choice == 2)
System.out.println("Please enter the address:");
String a = sc.nextLine();
System.out.println("Please enter the square footage:");
double f = sc.nextDouble();
System.out.println("Please enter the value:");
double v = sc.nextDouble();
Dwelling x = new Dwelling(a,f,v);
hList.add(x);
//
//insert
if (choice == 3)
System.out.println("Please enter the address:");
String ad = sc.nextLine();
System.out.println("Please enter the square footage:");
double fo = sc.nextDouble();
System.out.println("Please enter the value:");
double va = sc.nextDouble();
Dwelling y = new Dwelling(ad,fo,va);
System.out.println("Please enter the position to insert:");
int p = sc.nextInt();
hList.insert(y,p);
//delete
if (choice == 4)
System.out.println("Please enter the position to delete:");
int d = sc.nextInt();
hList.delete(d);
//exit
if (choice == 5)
return;
}
catch(ListException a)
{
System.out.println(a);
}
//use update method to update data file
}//end of manage method
//tostring
public void update() throws IOException
{
try
{
FileWriter d = new FileWriter(fileName);
dwellings = dList.toString();
for (int i = 0; i < dwellings.length(); i++)
d.write(dwellings.charAt(i));
d.close();
}
catch (IOException a)
{
throw new IOException();
}
}//end of update method
}//end of class
public class LList<T> //implements ListInterface<T>
{
private Node<T> head;
private Node<T> tail;
private int counter;
//constructor
public LList( )
{
head=null;
tail=null;
counter=0;
}
//add method
public void add( T m ) throws ListException
{
try
{
Node<T> temp = new Node<T>( );
temp.setData( m );
temp.setNext( null );
if ( head == null)
{
head = temp;
}
else
{
tail.setNext( temp );
}
tail = temp;
counter++;
}
catch(OutOfMemoryError e)
{
throw new ListException("Cannot add. No more memory");
}
}
//delete method
public T delete(int position) throws ListException
{
Node<T> current=head;
Node<T> before=null;
T temp;
if ( counter == 0 )
throw new ListException("Cannot delete. List is empty.");
if ( position >= 1 && position <= counter )
{
//the position is valid
if (counter == 1 ) //is there only 1 node
{
temp = head.getData();
head=null;
tail=null;
counter--;
return temp;
}
else
{
//there are at least 2 nodes
if ( position == 1 )
{
//there are at least 2 nodes and the user is trying to delete the first node
temp = head.getData();
head = head.getNext();
counter--;
return temp;
}
else
{
//there are at least 2 nodes but the user is not trying to delete the first
int k = 1;
while (k != position )
{
before = current;
current = current.getNext();
k++;
}
//we have arrived at the node to be deleted
temp = current.getData();
before.setNext( current.getNext() ); //gets rid of desired node
//Did we just delete last node
if ( before.getNext() == null )
tail=before;
counter--;
return temp;
}
}
}
else
{
//the position is invalid
throw new ListException("Cannot delete. Position is bad.");
}
}//end of delete method
//tostring method
public String toString()
{
if (head == null )
{
return "The list is empty.";
}
String t = "";
Node<T> temp;
temp=head;
while ( temp != null )
{
t += temp.getData() + "\n";
temp = temp.getNext();
}
return t;
}//end of toString
//insert method
public void insert( T item, int position ) throws ListException
{
try
{
if (counter == 0 )
throw new ListException("Cannot insert. List is empty.");
if (item == null )
throw new ListException("Cannot insert. Item is invalid.");
if (position <1 || position > counter )
throw new ListException("Cannot insert. Position is bad.");
Node<T> temp = new Node<T>();
temp.setData( item );
if (position == 1)
{
temp.setNext( head );
head = temp;
}
else
{
Node<T> before = head;
Node<T> current = head;
int k=1;
while( k != position )
{
before = current;
current = current.getNext();
k++;
}
temp.setNext( current );
before.setNext( temp );
}
}
catch(OutOfMemoryError e)
{
throw new ListException("Cannot insert. No more memory.");
}
}//end of insert method
public int Size( )
{
return counter;
}
} //end of LList
public class Node<T>
{
private T data;
private Node<T> next;
//default constructor
public Node()
{
data = null;
next = null;
}
public void setData( T p )
{
data = p;
}
public T getData()
{
return data;
}
public void setNext( Node<T> n)
{
next = n;
}
public Node<T> getNext()
{
return next;
}
} //end of the class
public class Dwelling
{
private String address;
private double footage;
private double value;
//constructor
Dwelling(String add, double f, double v) throws ListException
{
if (add == null || add.length() == 0)
{
throw new ListException("The address cannot be null");
}
else
{
this.address = add;
}
if(f <= 100)
{
throw new ListException("The squarefootage cannot be less then 100 ft.");
}
else
{
this.footage = f;
}
if(v <= 100000)
{
throw new ListException("The value cannot be less then $100000.");
}
else
{
this.value = v;
}
}
// Getter
public String getAddress()
{
return address;
}
// Setter
public void setAddress(String newAddress) throws ListException
{
if (newAddress == null || newAddress.length() == 0)
{
throw new ListException("The address cannot be null");
}
else
{
this.address = newAddress;
}
}
// Getter
public double getFootage()
{
return this.footage;
}
// Setter
public void setFootage(double foot) throws ListException
{
if(foot <= 100)
{
throw new ListException("The squarefootage cannot be less then 100 ft.");
}
else
{
this.footage = foot;
}
}
// Getter
public double getValue()
{
return this.value;
}
// Setter
public void setValue(double val) throws ListException
{
if(val <= 100000)
{
throw new ListException("The value cannot be less then $100000.");
}
else
{
this.value = val;
}
}
//toString
public String toString()
{
return address + "\n" + footage + "\n" + value + "\n";
}
}
Your if blocks are missing the closing brackets {} around them. Always place a bracket even if the if block has only one line for clarity.
Also, that if block should really be a switch block, but remember to always add a break for each of the choices in the switch.
You're declaring Scanner sc in the constructor and trying to use it on the Manage method, I'm not sure how that compiles.
In the Manage method you declare a Scanner in, you probably should use that scanner variable to scan values in your menu choices.
Also, for some reason you're using
int choice = Integer.parseInt(System.console().readLine());
to read the user choice, you should use Scanner in instead.
int choice = in.nextInt();
Edit: here are your if blocks rewritten:
switch (choice) {
case 1:
System.out.println(this);
break;
//add
case 2:
System.out.println("Please enter the address:");
String a = in.nextLine();
System.out.println("Please enter the square footage:");
double f = in.nextDouble();
System.out.println("Please enter the value:");
double v = in.nextDouble();
Dwelling x = new Dwelling(a, f, v);
hList.add(x);
break;
//
//insert
case 3:
System.out.println("Please enter the address:");
String ad = in.nextLine();
System.out.println("Please enter the square footage:");
double fo = in.nextDouble();
System.out.println("Please enter the value:");
double va = in.nextDouble();
Dwelling y = new Dwelling(ad, fo, va);
System.out.println("Please enter the position to insert:");
int p = sc.nextInt();
hList.insert(y, p);
break;
//delete
case 4:
System.out.println("Please enter the position to delete:");
int d = in.nextInt();
hList.delete(d);
break;
//exit
case 5:
return;
}
I am trying to read from a file and store the data into a single linked lists.
The data should have information about a user including id of type long, name of type string, and threat level of type int. Moreover, I am wondering how to read from the file and store into the linked list so that I can then do several operations.
my attempt:
class POI
public class POI {
private long id;
private String name;
private int level;
public POI(){
}
public POI(long n, String s, int l){
id = n;
name = s;
level = l;
}
public void setID (long n){
id = n;
}
public void setName (String s){
name = s;
}
public void setLevel (int l){
level = l;
}
public long getID(){
return id;
}
public String getName(){
return name;
}
public int getLevel(){
return level;
}
}
class POIList
public class POIList {
static private class Node {
int data;
Node next;
Node () {
data = 0;
next = null;
}
Node(int data, Node next) {
this.data = data;
this.next = next;
}
}
public static void print(Node head) {
while (head != null) {
System.out.print(head.data + ", ");
head = head.next;
}
System.out.println();
}
public Node insertNode(Node head, Node insertee, int position) {
if (position < 0) {
System.out.println("Invalid position given");
return head;
}
if (head == null) {
return insertee;
}
if (position == 0) {
insertee.next = head;
return insertee;
}
int i = 0;
Node current=head;
while (i < position - 1 && current.next != null) {
current = current.next;
i++;
}
if (i == position - 1) {
insertee.next = current.next;
current.next = insertee;
} else {
System.out.println("Position was not found.");
}
return head;
}
static Node swapNode(Node head,
int position1, int position2) {
if(position1 < 0 || position2 < 0)
System.out.println("InvalidPos");
Node n1 = null;
Node n2 = null;
Node prev1=null;
Node prev2=null;
int maxPosition = Math.max(position1, position2);
if (position1==maxPosition){
position1=position2;
position2=maxPosition;
}
Node temp=head;
for (int i = 0;i <= maxPosition; i++) {
if (temp == null) {
System.out.println("InvalidPos");
return head;
}
if (i==position1-1) prev1=temp;
if(i == position1) n1 = temp;
if (i==position2-1) prev2=temp;
if(i == position2) n2 = temp;
temp = temp.next;
}
temp = n2.next;
if (prev1!=null){
prev1.next=n2;
}else{
head=n2;
}
if (position2-position1==1){
n2.next=n1;
}else{
n2.next=n1.next;
}
if (prev2!=null){
prev2.next=n1;
}else{
head=n1;
}
n1.next=temp;
return head;
} // End of swapNode
public static Node removeNode(Node head, int position) {
if (position < 0 || head == null) {
System.out.println("Invalid position given");
return head;
}
if (position == 0) {
return head.next;
}
int i = 0;
Node current = head;
while (i < position - 1 && current.next != null) {
current = current.next;
i++;
}
if (current.next != null) {
current.next = current.next.next;
} else {
System.out.println("Position was not found.");
}
return head;
}
}
class AnalyzePOI
public class AnalyzePOI {
public static void main (String [] args) throws FileNotFoundException, IOException{
Scanner scan = new Scanner(System.in);
int choice;
System.out.print("Input filename:");
String filename = scan.nextLine();
File file = new File(filename);
Scanner reader = new Scanner(file);
POIList list = new POIList();
System.out.println("What operation would you like to implement? ");
choice = scan.nextInt();
switch (choice) {
case 1 : print(list) ;
break ;
case 2 : search(reader, list) ;
break ;
case 3 : insert(scan, list);
break ;
case 4 : swap(reader, list);
break ;
case 5 : remove1(reader, list);
break;
case 6 : remove2(reader, list);
break;
case 7 : output();
break;
case 8 :
System.out.println ("Program Terminated");
System.exit(0);
break;
}
start(scan,file, reader );
}
public static void start (Scanner scan, File file, Scanner reader){
String content = new String();
int count=1;
File file1 = new File("abc.txt");
LinkedList<String> list = new LinkedList<String>();
try {
Scanner sc = new Scanner(new FileInputStream(file));
while (sc.hasNextLine()){
content = sc.nextLine();
list.add(content);
}
sc.close();
}catch(FileNotFoundException fnf){
fnf.printStackTrace();
}
catch (Exception e) {
e.printStackTrace();
System.out.println("\nProgram terminated Safely...");
}
Collections.reverse(list);
Iterator i = (Iterator) list.iterator();
while (((java.util.Iterator<String>) i).hasNext()) {
System.out.print("Node " + (count++) + " : ");
System.out.println();
}
}
public static void print(POIList list) {
list.print(null);
}
public static void search(Scanner scan, POIList list) {
int id;
String name;
System.out.println("Do you want to enter id or name to search for record: ");
String answer = scan.next();
if (answer == "id"){
System.out.println ("Enter the id to find the record: ");
id = scan.nextInt();
}
else if (answer == "name"){
System.out.println("Enter the name to find the record: ");
name = scan.nextLine();
}
else{
System.out.println("Invalid input");
}
}
public static void insert(Scanner scan, POIList list) {
System.out.println("Enter the the location index ");
int index = 0;
long p1;
int level;
String name;
try {
System.out.println("Index: ") ;
index= scan.nextInt() ;
System.out.println("ID: ") ;
p1=scan.nextLong() ;
System.out.println("Name: ");
name = scan.nextLine();
System.out.println("Threat Level ") ;
level=scan.nextInt() ;
}
catch (InputMismatchException e) {
System.out.print("Invalid Input") ;
}
list.insertNode(null, null, index);
}
public static void swap(Scanner scan, POIList list) {
System.out.println("Enter index 1 to swap record: ");
int index1 = scan.nextInt();
System.out.println("Enter index 2 to swap record: ");
int index2 = scan.nextInt();
list.swapNode(null, index1, index2);
}
public static void remove1(Scanner scan, POIList list) {
int index= 0;
try{
System.out.println("Enter ID to remove a record: ") ;
index=scan.nextInt() ;
}
catch (InputMismatchException e) {
System.out.print("Invalid Input") ;
}
list.removeNode(null, index) ;
}
public static void remove2(Scanner scan, POIList list){
int index = 0;
try{
System.out.println("Enter threat level to remove a record: ");
index=scan.nextInt() ;
}
catch (InputMismatchException e){
System.out.println("Invalid Input");
}
list.removeNode(null, index) ;
}
public static void output() {
}
}
Assuming from your question, you would like to know how to read the file that contains "String" "long" and an "int" value. Let's suppose your input file would look like this as given below.
First, we need to know how the data would look like. I'm assuming that the I/P would look something like this
1 OneString 10
2 TwoSTring 20
Now, the order I'm assuming is "long" "String" "int" with a space in between for each line. Use bufferedReader for faster reading.
FileReader fr = new FileReader("yourFile.txt");
BufferedReader br = new BufferedReader(fr);
String curLine = br.next();
while(curLine!=null)
{
String[] tempLine = curLine.split(" ");
int threat = Integer.parseInt(tempLine[0]);
String user = tempLine[1];
long ID = Long.parseLong(tempLine[2]);
addPOI(ID,user,threat);
}
The addPOI method would look something like this.
public void addPOI(long ID, String user, int threatLevel)
{
list.addAtLast(new POI(ID,user,threadLevel));
}
And the list can be declared something like this,
List<POI> list = new List<POI>();
Greeting to everyone. I currently work on a program that sorting the emergency number of patients(the number that assigned by nurse when they enter the emergency room and this number determines the seriousness of their sickness too). However, if there are more than 1 patient who hold the same emergency numbers(eg: 2 patients hold emergency number 1), the one who came earlier should receive the treatment first. For this reason, I have 2 sortings, one is to sort the emergency number in ascending order and the other is to sort the time in ascending order too. But unfortunately the second sorting cannot work correctly.The following are the explanations for the type of emergency numbers:
Emergency number : 1 – Immediately life threatening
Emergency number : 2 – Urgent, but not immediately life threatening
Emergency number : 3 – Less urgent
So,now comes the coding part(Please note that this is a linkedlist)
Interface:
public interface ListInterface<T> {
public boolean add(T newEntry);
public boolean add(int newPosition, T newEntry);
public T remove(int givenPosition);
public void clear();
public boolean replace(int givenPosition, T newEntry);
public T getEntry(int givenPosition);
public boolean contains(T anEntry);
public int getLength();
public boolean isEmpty();
public boolean isFull();
}
LList class:
/**
* LList.java
* A class that implements the ADT list by using a chain of nodes,
* with the node implemented as an inner class.
*/
public class LList<T> implements ListInterface<T> {
private Node firstNode; // reference to first node
private int length; // number of entries in list
public LList() {
clear();
}
public final void clear() {
firstNode = null;
length = 0;
}
public boolean add(T newEntry) {
Node newNode = new Node(newEntry); // create the new node
if (isEmpty()) // if empty list
firstNode = newNode;
else { // add to end of nonempty list
Node currentNode = firstNode; // traverse linked list with p pointing to the current node
while (currentNode.next != null) { // while have not reached the last node
currentNode = currentNode.next;
}
currentNode.next = newNode; // make last node reference new node
}
length++;
return true;
}
public boolean add(int newPosition, T newEntry) { // OutOfMemoryError possible
boolean isSuccessful = true;
if ((newPosition >= 1) && (newPosition <= length+1)) {
Node newNode = new Node(newEntry);
if (isEmpty() || (newPosition == 1)) { // case 1: add to beginning of list
newNode.next = firstNode;
firstNode = newNode;
}
else { // case 2: list is not empty and newPosition > 1
Node nodeBefore = firstNode;
for (int i = 1; i < newPosition - 1; ++i) {
nodeBefore = nodeBefore.next; // advance nodeBefore to its next node
}
newNode.next = nodeBefore.next; // make new node point to current node at newPosition
nodeBefore.next = newNode; // make the node before point to the new node
}
length++;
}
else
isSuccessful = false;
return isSuccessful;
}
public T remove(int givenPosition) {
T result = null; // return value
if ((givenPosition >= 1) && (givenPosition <= length)) {
if (givenPosition == 1) { // case 1: remove first entry
result = firstNode.data; // save entry to be removed
firstNode = firstNode.next;
}
else { // case 2: givenPosition > 1
Node nodeBefore = firstNode;
for (int i = 1; i < givenPosition - 1; ++i) {
nodeBefore = nodeBefore.next; // advance nodeBefore to its next node
}
result = nodeBefore.next.data; // save entry to be removed
nodeBefore.next = nodeBefore.next.next; // make node before point to node after the
} // one to be deleted (to disconnect node from chain)
length--;
}
return result; // return removed entry, or
// null if operation fails
}
public boolean replace(int givenPosition, T newEntry) {
boolean isSuccessful = true;
if ((givenPosition >= 1) && (givenPosition <= length)) {
Node currentNode = firstNode;
for (int i = 0; i < givenPosition - 1; ++i) {
// System.out.println("Trace| currentNode.data = " + currentNode.data + "\t, i = " + i);
currentNode = currentNode.next; // advance currentNode to next node
}
currentNode.data = newEntry; // currentNode is pointing to the node at givenPosition
}
else
isSuccessful = false;
return isSuccessful;
}
public T getEntry(int givenPosition) {
T result = null;
if ((givenPosition >= 1) && (givenPosition <= length)) {
Node currentNode = firstNode;
for (int i = 0; i < givenPosition - 1; ++i) {
currentNode = currentNode.next; // advance currentNode to next node
}
result = currentNode.data; // currentNode is pointing to the node at givenPosition
}
return result;
}
public boolean contains(T anEntry) {
boolean found = false;
Node currentNode = firstNode;
while (!found && (currentNode != null)) {
if (anEntry.equals(currentNode.data))
found = true;
else
currentNode = currentNode.next;
}
return found;
}
public int getLength() {
return length;
}
public boolean isEmpty() {
boolean result;
if (length == 0)
result = true;
else
result = false;
return result;
}
public boolean isFull() {
return false;
}
public String toString() {
String outputStr = "";
Node currentNode = firstNode;
while (currentNode != null) {
outputStr += currentNode.data + "\n";
currentNode = currentNode.next;
}
return outputStr;
}
private class Node {
private T data;
private Node next;
private Node(T data) {
this.data = data;
this.next = null;
}
private Node(T data, Node next) {
this.data = data;
this.next = next;
}
} // end Node
} // end LList
Patient class:
public class Patient {
private int emergencyNo;
private int queueTime;
private String patientName;
private String patientIC;
private String patientGender;
private String patientTelNo;
private String patientAdd;
private String visitDate;
public Patient() {
}
public Patient(int emergencyNo, int queueTime, String patientName, String patientIC, String patientGender, String patientTelNo, String patientAdd, String visitDate)
{
this.emergencyNo = emergencyNo;
this.queueTime = queueTime;
this.patientName = patientName;
this.patientIC = patientIC;
this.patientGender = patientGender;
this.patientTelNo = patientTelNo;
this.patientAdd = patientAdd;
this.visitDate = visitDate;
}
//set methods
public void setQueueTime(int queueTime)
{
this.queueTime = queueTime;
}
public boolean setEmergencyNo(int emergencyNo)
{
boolean varEmergencyNo = true;
if (emergencyNo != 1 && emergencyNo != 2 && emergencyNo != 3)
{
varEmergencyNo = false;
System.out.println("Emergency number is in invalid format!");
System.out.println("Emergency number is either 1, 2 or 3 only!");
System.out.println("\n");
}
else
{
this.emergencyNo = emergencyNo;
}
return varEmergencyNo;
}
public boolean setPatientName(String patientName)
{
boolean varPatientName = true;
if (patientName.equals("") || patientName.equals(null))
{
varPatientName = false;
System.out.println("The patient name cannot be empty!\n");
}
else
{
this.patientName = patientName;
}
return varPatientName;
}
public boolean setPatientIC(String patientIC)
{
boolean varPatientIC = true;
if(!patientIC.matches("^[0-9]{12}$"))
{
varPatientIC = false;
System.out.println("IC is in invalid format!");
System.out.println("It must consist of 12 numbers only!\n");
}
else
{
this.patientIC = patientIC;
}
return varPatientIC;
}
public boolean setPatientGender(String patientGender)
{
boolean varPatientGender = true;
if(!patientGender.equals("F") && !patientGender.equals("f") && !patientGender.equals("M") && !patientGender.equals("m"))
{
varPatientGender = false;
System.out.println("Gender is in invalid format!");
System.out.println("It must be either 'M' or 'F' only!\n");
}
else
{
this.patientGender = patientGender;
}
return varPatientGender;
}
public boolean setPatientTelNo(String patientTelNo)
{
boolean varPatientTelNo = true;
if((!patientTelNo.matches("^01[02346789]\\d{7}$")) && (!patientTelNo.matches("^03\\d{8}$")))
{
varPatientTelNo = false;
System.out.println("Invalid phone number!");
System.out.println("It must be in the following format : 0167890990 / 0342346789!\n");
System.out.print("\n");
}
else
{
this.patientTelNo = patientTelNo;
}
return varPatientTelNo;
}
public boolean setPatientAdd(String patientAdd)
{
boolean varPatientAdd = true;
if (patientAdd.equals("") || patientAdd.equals(null))
{
varPatientAdd = false;
System.out.println("The patient address cannot be empty!\n");
}
else
{
this.patientAdd = patientAdd;
}
return varPatientAdd;
}
public void setVisitDate(String visitDate)
{
this.visitDate = visitDate;
}
//get methods
public int getQueueTime()
{
return this.queueTime;
}
public int getEmergencyNo()
{
return this.emergencyNo;
}
public String getPatientName()
{
return this.patientName;
}
public String getPatientIC()
{
return this.patientIC;
}
public String getPatientGender()
{
return this.patientGender;
}
public String getPatientTelNo()
{
return this.patientTelNo;
}
public String getPatientAdd()
{
return this.patientAdd;
}
public String getVisitDate()
{
return this.visitDate;
}
#Override
public String toString()
{
return (this.emergencyNo + "\t\t" + this.patientName + "\t\t" + this.patientIC +
"\t\t" + this.patientGender + "\t\t" + this.patientTelNo + "\t\t" + this.patientAdd + "\t\t" + this.visitDate);
}
public String anotherToString()
{
return (this.emergencyNo + "\t\t\t\t\t\t" + this.patientName + "\t\t\t " + this.visitDate);
}
}
EmergencyCmp(Comparator)--->use for sorting the emergency numbers of the patients
import java.util.Comparator;
public class EmergencyCmp implements Comparator<Patient>
{
#Override
public int compare(Patient p1, Patient p2)
{
if(p1.getEmergencyNo() > p2.getEmergencyNo())
{
return 1;
}
else
{
return -1;
}
}
}
QueueCmp(Comparator)--->use for sorting the arrival time of the patients
import java.util.Comparator;
public class QueueCmp implements Comparator<Patient>
{
#Override
public int compare(Patient p1, Patient p2)
{
if(p1.getQueueTime() > p2.getQueueTime())
{
return 1;
}
else
{
return -1;
}
}
}
Main function:
import java.util.Calendar;
import java.util.Scanner;
import java.util.Arrays;
import java.util.*;
public class DSA {
public DSA() {
}
public static void main(String[] args) {
//patient's attributes
int emergencyNo;
int queueTime;
String patientName;
String patientIC;
String patientGender;
String patientTelNo;
String patientAdd;
String visitDate;
//counter
int j = 0;
int x = 0;
int y = 0;
int z = 0;
int count1 = 0;
int count2 = 0;
int count3 = 0;
int countEnteredPatient = 1;
int totalCount = 0;
//calendar
int nowYr, nowMn, nowDy, nowHr, nowMt, nowSc;
//others
boolean enterNewPatient = true;
String continueInput;
boolean enterNewPatient1 = true;
String continueInput1;
boolean continueEmergencyNo;
Scanner scan = new Scanner(System.in);
ListInterface<Patient> patientList = new LList<Patient>();
ListInterface<Patient> newPatientList = new LList<Patient>();
Patient[] patientArr1 = new Patient[10000];
Patient[] patientArr2 = new Patient[10000];
Patient[] patientArr3 = new Patient[10000];
Patient tempoPatient;
do{
//do-while loop for entering new patient details after viewing patient list
System.out.println("Welcome to Hospital Ten Stars!\n");
do{
//do-while loop for entering new patient details
System.out.println("Entering details of patient " + countEnteredPatient);
System.out.println("===================================\n");
Calendar calendar = Calendar.getInstance();
nowYr = calendar.get(Calendar.YEAR);
nowMn = calendar.get(Calendar.MONTH);
nowDy = calendar.get(Calendar.DAY_OF_MONTH);
nowHr = calendar.get(Calendar.HOUR);
nowMt = calendar.get(Calendar.MINUTE);
nowSc = calendar.get(Calendar.SECOND);
queueTime = calendar.get(Calendar.MILLISECOND);
visitDate = nowDy + "/" + nowMn + "/" + nowYr + ", " + nowHr + ":" + nowMt + ":" + nowSc;
//input emergency number
do{
tempoPatient = new Patient();
continueEmergencyNo = false;
int EmergencyNoOption;
try
{
do{
System.out.print("Please select 1 – Immediately life threatening, 2 – Urgent, but not immediately life threatening or 3 – Less urgent(Eg: 1) : ");
EmergencyNoOption = scan.nextInt();
scan.nextLine();
System.out.print("\n");
}while(tempoPatient.setEmergencyNo(EmergencyNoOption) == false);
}
catch(InputMismatchException ex)
{
System.out.print("\n");
System.out.println("Invalid input detected.");
scan.nextLine();
System.out.print("\n");
continueEmergencyNo = true;
}
}while(continueEmergencyNo);
//input patient name
do{
System.out.print("Patient name(Eg: Christine Redfield) : ");
patientName = scan.nextLine();
System.out.print("\n");
}while(tempoPatient.setPatientName(patientName) == false);
//input patient ic no
do{
System.out.print("Patient IC number(Eg: 931231124567) : ");
patientIC = scan.nextLine();
System.out.print("\n");
}while(tempoPatient.setPatientIC(patientIC) == false);
//input patient gender
do{
System.out.print("Patient gender(Eg: M) : ");
patientGender = scan.nextLine();
System.out.print("\n");
}while(tempoPatient.setPatientGender(patientGender) == false);
//input patient tel. no
do{
System.out.print("Patient tel.No(without'-')(Eg: 0162345678/0342980123) : ");
patientTelNo = scan.nextLine();
System.out.print("\n");
}while(tempoPatient.setPatientTelNo(patientTelNo) == false);
//input patient address
do{
System.out.print("Patient address(Eg: 4-C9 Jln Besar 123, Taman Besar, 56000 Kuala Lumpur) : ");
patientAdd = scan.nextLine();
System.out.print("\n");
}while(tempoPatient.setPatientAdd(patientAdd) == false);
tempoPatient.setQueueTime(queueTime);
tempoPatient.setVisitDate(visitDate);
patientList.add(tempoPatient);
//decide whether want to enter a new patient or not
do{
System.out.print("Do you want to enter another new patient?(Eg: Y/N) : ");
continueInput = scan.nextLine();
if(continueInput.equals("Y") || continueInput.equals("y"))
{
enterNewPatient = true;
System.out.print("\n");
}
else if(continueInput.equals("N") || continueInput.equals("n"))
{
enterNewPatient = false;
}
else
{
System.out.println("\n");
System.out.println("Please enter Y/N only.\n");
}
}while(!continueInput.equals("Y") && !continueInput.equals("y") && !continueInput.equals("N") && !continueInput.equals("n"));
countEnteredPatient++;
}while(enterNewPatient); //end do-while loop for entering new patient details
System.out.println("\nWaiting list of patient will be displayed soon.\n");
try{
Thread.sleep(1000);
}
catch (Exception e)
{
}
System.out.println("Waiting list of patients");
System.out.println("========================\n");
System.out.println("Number\t\tEmergency number\t\tPatient name\t\t ArrivalTime");
System.out.println("============================================================================");
for(int i = 1; i <= patientList.getLength(); i++)
{
System.out.println(i + "\t\t\t" + patientList.getEntry(i).anotherToString());
}
do{
System.out.print("\nSo, now do you want to enter another new patient?(Eg: Y/N) : ");
continueInput1 = scan.nextLine();
if(continueInput1.equals("Y") || continueInput1.equals("y"))
{
enterNewPatient1 = true;
System.out.print("\n");
}
else if(continueInput1.equals("N") || continueInput1.equals("n"))
{
enterNewPatient1 = false;
}
else
{
System.out.println("\n");
System.out.println("Please enter Y/N only.\n");
}
}while(!continueInput1.equals("Y") && !continueInput1.equals("y") && !continueInput1.equals("N") && !continueInput1.equals("n"));
}while(enterNewPatient1);//end do-while loop for entering new patient details after viewing patient list
System.out.println("\nNow rearranging the list based on the seriouness and their arrival time.");
try{
Thread.sleep(1000);
}
catch (Exception e)
{
}
//create an unsorted array
Patient[] tempoPatientArr = new Patient[patientList.getLength()];
//copy the contents of patientList into tempoPatientArr
for(int i = 1; i <= patientList.getLength(); i++ )
{
tempoPatientArr[i-1] = patientList.getEntry(i);
}
//sort tempoPatientArr
Arrays.sort(tempoPatientArr, new EmergencyCmp());
//the above part until this comment line does not have problem
//check the emergency no and then categorise accordingly
for(int i = 0; i < tempoPatientArr.length; i++)
{
if(tempoPatientArr[i].getEmergencyNo() == 1)
{
patientArr1[x] = tempoPatientArr[i];
x++;
}
else if(tempoPatientArr[i].getEmergencyNo() == 2)
{
patientArr2[y] = tempoPatientArr[i];
y++;
}
else if(tempoPatientArr[i].getEmergencyNo() == 3)
{
patientArr3[z] = tempoPatientArr[i];
z++;
}
}
//to check how many !null elements by using count for 3 sub-arrays
for(int i = 0; i < patientArr1.length; i++)
{
if(patientArr1[i] != null)
{
count1++;
}
else
{
break;
}
}
for(int i = 0; i < patientArr2.length; i++)
{
if(patientArr2[i] != null)
{
count2++;
}
else
{
break;
}
}
for(int i = 0; i < patientArr3.length; i++)
{
if(patientArr3[i] != null)
{
count3++;
}
else
{
break;
}
}
//new array with elimination of null values
Patient[] newPatientArr1 = new Patient[count1];
Patient[] newPatientArr2 = new Patient[count2];
Patient[] newPatientArr3 = new Patient[count3];
//copy the contents of old sub arrays(the arrays with null values) into the new sub arrays(without null values)
for(int i = 0; i < newPatientArr1.length; i++)
{
newPatientArr1[i] = patientArr1[i];
}
for(int i = 0; i < newPatientArr2.length; i++)
{
newPatientArr2[i] = patientArr2[i];
}
for(int i = 0; i < newPatientArr3.length; i++)
{
newPatientArr3[i] = patientArr3[i];
}
totalCount = count1 + count2 + count3;
//array that used to combine all the sub-arrays
Patient[] newPatientArr = new Patient[totalCount];
//sort all sub new arrays
Arrays.sort(newPatientArr1, new QueueCmp());
Arrays.sort(newPatientArr2, new QueueCmp());
Arrays.sort(newPatientArr3, new QueueCmp());
//combine the contents of sub new arrays into the newPatientArr array
do{
for (int i = 0; i < count1; i++)
{
newPatientArr[j] = newPatientArr1[i];
j++;
}
for (int b = 0; b < count2; b++)
{
newPatientArr[j] = newPatientArr2[b];
j++;
}
for (int c = 0; c < count3; c++)
{
newPatientArr[j] = newPatientArr3[c];
j++;
}
}while(j < totalCount);
//relink the nodes
for(int i = 0; i < newPatientArr.length; i++)
{
newPatientList.add(newPatientArr[i]);
}
System.out.println("\nSorted waiting list of patients");
System.out.println("===============================\n");
System.out.println("Number\t\tEmergency number\t\tPatient name\t\t ArrivalTime");
System.out.println("============================================================================");
for(int i = 1; i <= newPatientList.getLength(); i++)
{
System.out.println(i + "\t\t\t" + newPatientList.getEntry(i).anotherToString());
}
}
}
Interface and LList class definitely do not have problems. So everyone can skip the 2 parts.
For the main function, I have a comment like this:
//the above part until this comment line does not have problem
When you all see the comment, that means the previous code does not have problem and you all may skip it and below is an attachment of the result that I got earlier:
So, from the picture you all can see that the sorting of arrival time is not correct. I hope that I can know why does this problem occurs since I cannot figure it out by myself. Thanks to all of you first.
So, after taking the advice of #Scott Hunter, I have made the following modification to the EmergencyCmp:
#Override
public int compare(Patient p1, Patient p2)
{
int value = 0;
if(p1.getEmergencyNo() > p2.getEmergencyNo())
{
value = 1;
}
else if(p1.getEmergencyNo() < p2.getEmergencyNo())
{
value = -1;
}
else if(p1.getEmergencyNo() == p2.getEmergencyNo())
{
if(p1.getQueueTime() > p2.getQueueTime())
{
return 1;
}
else
{
return -1;
}
}
return value;
}
However, the time sorting still produce a wrong result.
As I understand it (which I may not; you provided a LOT of extraneous stuff), it looks like you are trying to perform 2 distinct sorts, one after the other, such that the second is undoing the work of the first. Instead, you should define a single Comparator which compares emergency numbers and, only if they are the same, compares arrival times.
the program I am working on is supposed to have you enter a gender and name of a person ex: "m john"
And then it is supposed to separate the males and females and print out just the name separately.
I have am comparing the first character in the string and then using enqueue to add a substring to either a male queue or a female queue and then I am trying to print each queue by printing the dequeued substring. but I get an error that my queue is empty even though I have added strings in my for loop.
public class GenderSorter
{
public static void main(String[] args)
{
int numElements;
int maleCount = 0;
int femaleCount = 0;
Scanner keyboard = new Scanner(System.in);
System.out.println("How many people are you adding: ");
numElements = keyboard.nextInt();
keyboard.nextLine();
ArrayBndQueue male = new ArrayBndQueue<>();
ArrayBndQueue female = new ArrayBndQueue<>();
for(int index = 1; index <= numElements; index++)
{
/*
System.out.println("Enter a gender and name (ex: f jenny)");
String name = keyboard.nextLine();
System.out.println(name);
*/
System.out.println("Enter a gender and name (ex: f jenny)");
String name = keyboard.nextLine();
char character = name.charAt(0);
if(character == 'f')
{
female.enqueue(name.substring(2));
femaleCount++;
}
else
{
male.enqueue(name.substring(2));
maleCount++;
}
}
System.out.println("Females: " + "\n");
for(int index2 = 0; index2 <= femaleCount; index2++)
{
System.out.print(female.dequeue());
}
System.out.println("Males: " + "\n");
for(int index3 = 0; index3 <= maleCount; index3++)
{
System.out.print(male.dequeue());
}
}
}
Here is my ArrayBndQueue:
public class ArrayBndQueue<T> implements BoundedQueueInterface<T>
{
protected final int DEFCAP = 100;
protected T[] queue;
protected int numElements = 0;
protected int front = 0;
protected int rear;
public ArrayBndQueue()
{
queue = (T[]) new Object[DEFCAP];
rear = DEFCAP -1;
}
public ArrayBndQueue(int maxSize)
{
queue = (T[]) new Object[maxSize];
rear = maxSize -1;
}
public void enqueue(T element)
{
if(isFull())
{
throw new QueueOverflowException("Enqueue " + "attempted on full queue");
}
else
{
rear = (rear + 1) % queue.length;
queue[rear] = element;
numElements++;
}
}
public boolean isFull()
{
return (numElements == queue.length);
}
public boolean isEmpty()
{
return (numElements == 0);
}
public T dequeue()
{
if(isEmpty())
{
throw new QueueUnderflowException("Dequeue" +
" attempted on empty queue!");
}
else
{
T toReturn = queue[front];
queue[front] = null;
front = (front + 1) % queue.length;
numElements--;
return toReturn;
}
}
}
Perhaps it's not the only problem, but
for(int index2 = 0; index2 <= femaleCount; index2++)
should be
for(int index2 = 0; index2 < femaleCount; index2++)
As it is, the last dequeue would give you the QueueUnderflowException, since you are trying to dequeue n+1 items from a queue that contains only n.
Same problem exists for both male and female loops.
I'm supposed to order the numbers inserted in this list. I have to order it backwards too. I've been trying to do it for the last couple of hours but I haven't come up with anything. I'm a beginner and to me the hardest part is to order it using of its pointers.
public class MyList {
private static class MyList
{
public int num;
public MyList nextn;
}
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
MyList start = null;
MyList end = null;
MyList aux;
MyList before;
int op, number, found;
do{
System.out.println("1- insert number in the beginning list");
System.out.println("2- insert in the end of the list");
System.out.println("3- query list");
System.out.println("4- remove from list");
System.out.println("5- empty list");
System.out.println("6- exit");
System.out.print("choose: ");
op = input.nextInt();
if(op < 1||op>6)
{
System.out.println("invalid number");
}
if(op == 1)
{
System.out.println("type the number to be inserted in the beginning of the list");
MyList newl = new MyList();
newl.num = input.nextInt();
if(start == null)
{
start = newl;
end = newl;
newl.nextn = null;
}
else
{
newl.nextn = start;
start = newl;
}
System.out.println("number inserted");
}
if(op == 2)
{
System.out.println("type the number to be inserted in the end of the list");
MyList newl = new MyList();
newl.num = input.nextInt();
if(start == null)
{
start = newl;
end = newl;
newl.nextn = null;
}
else
{
end.nextn = newl;
end = newl;
newl.nextn = null;
}
System.out.println("number inserted");
}
if(op == 3)
{
if(start == null)
{
System.out.println("list is empty");
}
else
{ System.out.println("\nquerying the list\n");
aux = start;
while(aux!=null)
{
System.out.print(aux.num+ " ");
aux = aux.nextn;
}
}
}
if(op == 4)
{
if(start == null)
{
System.out.println("list is empty");
}
else
{
System.out.println("\ntype the number to be removed:\n");
number = input.nextInt();
aux = start;
before = null;
found = 0;
while(aux!=null)
{
if(aux.num == number)
{
found = found +1;
if(aux == start)
{
start = aux.nextn;
aux = start;
}
else if(aux == end)
{
before.nextn = null;
end = before;
aux = null;
}
else
{
before.nextn =aux.nextn;
aux = aux.nextn;
}
}
else
{
before = aux;
aux =aux.nextn;
}
}
if(found ==0) {
System.out.append("number not found");
}
else if(found ==1)
{
System.out.append("number removed once!");
}
else
{
System.out.append("number removed "+found+" times!");
}
}
}
if(op == 5)
{
if(start == null)
{
System.out.println("empty list");
}
else
{
start = null;
System.out.println("emptied list");
}
}
} while(op !=6);
}
First - do something with your naming conventions.
You have two classes with the same name MyList (one is public, one is Inner). That's why I suggest changing the Inners class name to MyListElement:
private class MyListElement
{
private final Integer value;
private MyListElement nextElement;
private MyListElement(final Integer value)
{
this.value = value;
}
}
No more nextn or num. List elements have values and nextElements. Also - their values are final (cannot be changed). No more start, op, found, aux and so on. Those names mean **** and are not helpful, and are messing up the code.
Second - don't do everything in a main method.
It's bad practice. It forces you to use static fields and methods. Create an object in main method and let that object do the work for you:
public class MyList
{
private Scanner userInput;
private Integer selectedOption;
private MyListElement firstElement = null;
private boolean exitRequested = false;
public static void main(final String[] args)
{
MyList myList = new MyList(new Scanner(System.in));
myList.run();
}
private MyList(final Scanner userInput)
{
this.userInput = userInput;
}
//other methods and classes
}
Third - how should your code work?
As simple as possible. That said:
public void run()
{
do
{
promptUserForOperation();
processSelectedOperation();
} while(!exitRequested);
}
Simple enough?
Fourth - You know how to prompt. How to process?
Again - as simple as possible. That said:
private void processSelectedOption()
{
switch (selectedOption)
{
case 1:
case 2:
{
addNewElement();
} break;
case 3:
{
printList();
} break;
case 4:
{
removeElement();
} break;
case 5:
{
clearList();
} break;
case 6:
{
exit();
} break;
default:
{
printWrongOperationSelected();
}
}
}
Finally - how to sort?
private void addNewElement()
{
//getting the input
System.out.print("Please type the number to be added to the list: ");
Integer newValue = null;
while(newValue == null)
{
try
{
newValue = Integer.parseInt(userInput.nextLine());
}
catch (final Exception e)
{
System.out.println("Wrong value. Please insert new value.");
}
}
//creating new element based on the input
MyListElement newElement = new MyListElement(newValue);
//if not first
if (firstElement != null)
{
placeElementInList(newElement);
}
else
{
firstElement = newElement; //if first
}
}
//if not first
private void placeElementInList(final MyListElement newElement)
{
//if smaller than first
if (newElement.value < firstElement.value)
{
newElement.nextElement = firstElement; //new points to first
firstElement = newElement; //and becomes first
}
else
{
MyListElement previousElement = firstElement; //have to remember previous element
MyListElement elementInList = firstElement.nextElement; //currently checked.
while (elementInList != null)
{
if (newElement.value < elementInList.value) //if new element is smaller that currently checked
{
break; //break - put it in current position.
}
previousElement = elementInList; //if not, move forward, substitute variables
elementInList = elementInList.nextElement;
}
previousElement.nextElement = newElement; //set the new element at the proper position
newElement.nextElement = elementInList; //
}
}
The remove method is almost the same.
And that's all.
You can do it you're way - using the sorting method presented - but I'd suggest learning good habbits as soon as possible. And that is naming your classes/methods/fields/variables properly (they don't have to be short, use ctrl+space), and fragmenting the code to the smallest parts possible. Mind that the above code is far from being perfect - much can be improved.
SPOILER
Whole (working) code:
package test;
import java.util.Scanner;
public class MyList
{
private Scanner userInput;
private Integer selectedOption;
private MyListElement firstElement = null;
private boolean exitRequested = false;
public static void main(final String[] args)
{
new MyList(new Scanner(System.in)).run();
}
private MyList(final Scanner userInput)
{
this.userInput = userInput;
}
public void run()
{
do
{
promptUserForOption();
processSelectedOption();
} while(!exitRequested);
}
private void promptUserForOption()
{
System.out.println("");
System.out.println("1 - insert number in the beginning list");
System.out.println("2 - insert in the end of the list");
System.out.println("3 - query list");
System.out.println("4 - remove from list");
System.out.println("5 - empty list");
System.out.println("6 - exit");
System.out.print("Please choose option: ");
try
{
selectedOption = Integer.parseInt(userInput.nextLine());
}
catch (final Exception e)
{
printWrongOperationSelected();
selectedOption = -1;
}
}
private void printWrongOperationSelected()
{
System.out.println("Wrong operation selected.");
}
private void processSelectedOption()
{
switch (selectedOption)
{
case 1:
case 2:
{
addNewElement();
} break;
case 3:
{
printList();
} break;
case 4:
{
removeElement();
} break;
case 5:
{
clearList();
} break;
case 6:
{
exit();
} break;
default:
{
printWrongOperationSelected();
}
}
}
private void addNewElement()
{
System.out.print("Please type the number to be added to the list: ");
Integer newValue = null;
while(newValue == null)
{
try
{
newValue = Integer.parseInt(userInput.nextLine());
}
catch (final Exception e)
{
System.out.println("Wrong value. Please insert new value.");
}
}
MyListElement newElement = new MyListElement(newValue);
if (firstElement != null)
{
placeElementInList(newElement);
}
else
{
firstElement = newElement;
}
}
private void placeElementInList(final MyListElement newElement)
{
if (newElement.value < firstElement.value)
{
newElement.nextElement = firstElement;
firstElement = newElement;
}
else
{
MyListElement previousElement = firstElement;
MyListElement elementInList = firstElement.nextElement;
while (elementInList != null)
{
if (newElement.value < elementInList.value)
{
break;
}
previousElement = elementInList;
elementInList = elementInList.nextElement;
}
previousElement.nextElement = newElement;
newElement.nextElement = elementInList;
}
}
private void printList()
{
if (firstElement == null)
{
System.out.println("No elements in the list.");
}
else
{
MyListElement elementInList = firstElement;
while (elementInList != null)
{
System.out.print(elementInList.value + ", ");
elementInList = elementInList.nextElement;
}
System.out.println("");
}
}
private void removeElement()
{
System.out.print("Please type the number to be removed from the list: ");
Integer valueToRemove = null;
while(valueToRemove == null)
{
try
{
valueToRemove = Integer.parseInt(userInput.nextLine());
}
catch (final Exception e)
{
System.out.println("Wrong value. Please insert value to remove.");
}
}
if (firstElement == null)
{
System.out.println("No elements in the list. None can be removed.");
}
else
{
boolean found = false;
if (firstElement.value.equals(valueToRemove))
{
firstElement = firstElement.nextElement;
found = true;
}
else
{
MyListElement previousElement = firstElement;
MyListElement elementInList = firstElement.nextElement;
while (elementInList != null)
{
if (elementInList.value.equals(valueToRemove))
{
previousElement.nextElement = elementInList.nextElement;
found = true;
break;
}
previousElement = elementInList;
elementInList = elementInList.nextElement;
}
}
if (!found)
{
System.out.println("Value " + valueToRemove + " is not in the list.");
return;
}
else
{
System.out.println("Value removed.");
}
}
}
private void clearList()
{
firstElement = null;
}
private void exit()
{
exitRequested = true;
}
private class MyListElement
{
private final Integer value;
private MyListElement nextElement;
private MyListElement(final Integer value)
{
this.value = value;
}
}
}
EDIT(from Phone)
private void printInReverse()
{
MyListElement tmpElement=firstElement;
MyListElement previousElement=tmpElement.nextElement;
while (previousElement!=null)
{
previousElement.nextElement=tmpElement;
tmpElement =previousElement;
previousElement=previousElenent.nextElement;
}
MyListElement firstReverseElement=tmpElement;
//loop like in the normal print loop but using firstReverseElement as starting point. You can create print methodthat would take First element as param.
}
EDIT - REVERSE ORDER COMPLETE:
private void printList()
{
printListFromElement(firstElement);
}
private void printListFromElement(final MyListElement firstElementToPrint)
{
if (firstElementToPrint == null)
{
System.out.println("No elements in the list.");
}
else
{
MyListElement elementInList = firstElementToPrint;
while (elementInList != null)
{
System.out.print(elementInList.value + ", ");
elementInList = elementInList.nextElement;
}
System.out.println("");
}
}
private void printListInReverse()
{
if (firstElement == null)
{
System.out.println("No elements in the list.");
}
else
{
MyListElement fistElementInReverse = new MyListElement(firstElement.value);
MyListElement previousElement;
MyListElement elementInOriginalList = firstElement;
while (elementInOriginalList.nextElement != null)
{
previousElement = fistElementInReverse;
fistElementInReverse = new MyListElement(elementInOriginalList.nextElement.value);
fistElementInReverse.nextElement = previousElement;
elementInOriginalList = elementInOriginalList.nextElement;
}
printListFromElement(fistElementInReverse);
}
}
Here in the reversing loop you have to create new MyListElementObjects. You get infinite loop/break original list/get null pointer if you don't do that, as you only change references in the original list.