I'm writing a program to work as a sales management program at a movie store. It is supposed to read a .dat file into the DVDmenu.java file and it uses a case/switch statement to handle the menu. I've been writing and rewriting this program but I can't seem to find the linkage errors in my code that is preventing it from compiling.
import java.io.*; // this includes the input output library files
import java.util.*; // this includes the utility libraray files
public class DVDmenu
{
public static void main(String[] args)
{
Scanner scanF = null; // This creates an empty scanner for the .dat system.
PrintWriter pw = null; // This creates a print writer to write info to the .dat
String fileIn; // this creates the file input name of the .dat
LinkedList DVDinv = new LinkedList(); // this creates a linked list
if(args.length != 1)
{
System.out.println("USAGE: DVD Menu <input_file>");
System.exit(1);
}
fileIn = args[0];
try
{
scanF = new Scanner(new File(fileIn));
}
catch (FileNotFoundException e)
{
System.out.println("Error: file \"" + fileIn + "\" does not exist");
System.exit(2);
}
while(scanF.hasNext())
{
String title = scanF.nextLine();
DVD newDVD = new DVD(title);
DVDinv.insert(newDVD);
}
String input = "null";
System.out.println("Type a letter then press enter");
System.out.println("H:help,L:list,I:inquire, A:add, S:sell,Q:quit.");
scanF.close();
Scanner key = new Scanner(System.in);
do
{
char in = key.nextLine().charAt(0);;
switch(in)
{
case 'H':
case 'h':
System.out.println("Enter H for help, L to list, I <movieTitle> to"
+ " inquire, A <movieTitle> to add, S <movieTitle> to sell, M <amount>"
+ " <movieTitle> and Q to quit.");
break;
case 'L':
case 'l':
if(!DVDinv.isEmpty())
{
Node<DVD> head = DVDinv.getHead();
while(head != null)
{
System.out.println( head.getDVD().getStock() + " Has "
+ head.getDVD().getTitle() + "copies in stock.");
head = head.getNext();
}
}
break;
case 'I':
case 'i':
String title = input.substring(2);
DVD newDVD = new DVD(newDVD);
System.out.println(head.getDVD().getTitle() + " has "
+ head.getDVD().getStock() + " copies in stock.");
break;
case 'A':
case 'a':
String title = input.substring(2);
DVD newDVD = new DVD(title);
DVDinv.insert(newDVD);
System.out.println("One Copy of " + head.getDVD().getTitle() + " was added.");
break;
case 'S':
case 's':
String title = input.substring(2);
DVD newDVD = new DVD(title);
DVDinv.delete(newDVD);
System.out.println("All copies of " + head.getDVD().getTitle() + " have been sold.");
break;
case 'Q':
case 'q':
System.out.println("Thank you for using this system.");
break;
}
}while(in != 'Q' && in != 'q');
try
{
pw = new PrintWriter (new FileWriter(fileIn));
}
catch (IOException e)
{
System.out.println("General I/O exception: " + e.getMessage());
}
Node<DVD> current = DVDinv.getHead();
while(current != null)
{
for(int i=0; i < current.getDVD().getStock(); i++)
{
pw.println(current.getDVD().getTitle());
}current = current.getNext();
}pw.close();
}
}
public class DVD implements Comparable<DVD>
{
private String title; // this sets a private string variable for a movie
private int Stock; // this sets a private int variable for the amount
public DVD(String movieTitle)
{
title = movieTitle; // this sets the movie title to title
Stock = 1; // this automatically sets the # of copies to 1
}
public String getTitle()
{
return title; // this returns the movie title to the user
}
public int getStock()
{
return Stock; // returns the amount of films are available for sale
}
public void setStock(int newStock)
{
Stock = newStock; // adds inventory amount to available films for sale
}
public int compareTo(DVD DVDtoCompare)
{
return title.compareToIgnoreCase(DVDtoCompare.getTitle()); // compares two film title strings to
// determine which one is alphabetically above or below one another.
}
}
public class Node<DVD extends Comparable<DVD>>
{
private DVD dvd;
private Node<DVD> next;
public Node(DVD movieTitle)
{
dvd = movieTitle;
next = null;
}
public void setDVD(DVD newDVD)
{
dvd = newDVD;
}
public void setNext(Node<DVD> newNext)
{
next = newNext;
}
public DVD getDVD()
{
return dvd;
}
public Node<DVD> getNext()
{
return next;
}
}
public class LinkedList
{
private Node<DVD> head;
public LinkedList()
{
head = null;
}
public Node<DVD> contains(DVD thedvd)
{
Node<DVD> current = head;
while(current != null)
{
if(thedvd.compareTo(current.getDVD()) == 0)
{
return current;
}
else if(thedvd.compareTo(current.getDVD()) < 0)
{
return null;
}
else
{
current = current.getNext();
}
}
return null;
}
public void insert(DVD thedvd)
{
Node<DVD> toAdd = new Node<DVD>(thedvd);
if(this.isEmpty())
{
head = toAdd;
}
else
{
Node<DVD> current = head;
Node<DVD> previous = null;
while(current != null)
{
if(thedvd.compareTo(current.getDVD()) == 0)
{
current.getDVD().setStock(current.getDVD().getStock() + 1);
return;
}
else if(thedvd.compareTo(current.getDVD()) < 0)
{
toAdd.setNext(current);
if(previous != null)
{
previous.setNext(toAdd);
}
else
{
head = toAdd;
}
return;
}
else
{
previous = current;
current = current.getNext();
}
}
previous.setNext(toAdd);
}
}
public DVD delete(DVD thedvd)
{
if(this.isEmpty())
{
return null;
}
if (thedvd.compareTo(head.getDVD()) == 0)
{
if(head.getDVD().getStock() == 1)
{
head = head.getNext();
return thedvd;
}
else
{
head.getDVD().setStock(head.getDVD().getStock() - 1);
return thedvd;
}
}
Node<DVD> previous = head;
Node<DVD> current = head.getNext();
while(current != null)
{
if(thedvd.compareTo(current.getDVD()) == 0)
{
if(current.getDVD().getStock() == 1)
{
previous.setNext(current.getNext());
return thedvd;
}
else
{
current.getDVD().setStock(current.getDVD().getStock() - 1);
}
}
else if(thedvd.compareTo(current.getDVD()) < 0)
{
return null;
}
else
{
previous = current;
current = current.getNext();
}
}
return null;
}
public boolean isEmpty()
{
return (head==null);
}
public Node getHead()
{
return head;
}
public int getStock(DVD thedvd)
{
if(this.contains(thedvd) != null)
{
return ((this.contains(thedvd)).getDVD()).getStock();
}
return 0;
}
}
You create the variable head inside your case 'L': case 'l': if block. It is a local variable and not visible anywhere outside of this if block, especially not visible in the next case 'I': case 'i': where you try to access it:
System.out.println(head.getDVD().getTitle() + " has "
+ head.getDVD().getStock() + " copies in stock.");
Related
i have a problem with this method, i want to delete student information from the linked list but it is not working and the output also is not the same as the required one
can you spot the error?
public void deleteStudent (String id){
Node help_ptr = head;
if (head == null) {
if (head == tail) {
if (head.student.id.equals(id))
System.out.println(head.student.id + " Deleted!");
head = tail = null;
return;
} else if (head.student.id.equals(id)) {
// if “value” is in the first node
System.out.println(head.student.id + " Deleted!");
head = head.next;
head.prev = null;
return;
} else if (tail.student.id.equals(id)) {
// if “value” is in the last node tail = tail.prev;
System.out.println(tail.student.id + " Deleted!");
tail.next = null;
return;
} else {
while (help_ptr != null) {
if (help_ptr.student.id.equals(id)) {
System.out.println(help_ptr.student.id + " Deleted!");
help_ptr.prev.next = help_ptr.next;
help_ptr.next.prev = help_ptr.prev;
return;
}
help_ptr = help_ptr.next;
}
}
the output that is required:
********* Delete Student **********
0000001 Deleted
********* Delete Student **********
0000003 Deleted
********* Delete Student **********
00000023 Not found in the list
the output that i get:
************** Delete Student **************
************** Delete Student **************
************** Delete Student **************
main class:
package classreport;
import java.util.*;
import java.io.*;
public class ClassReport {
/*
* #param args the command line arguments
*/
public static void main(String[] args) {
String id;
String name;
Double gpa;
StudentList list = new StudentList();
try {
// create file object
File f = new File("studentsList.txt");
// create scanner object that reads from file
Scanner sf = new Scanner(f);
// start reading
String line;
while (sf.hasNextLine()) {
while ((line = sf.nextLine().trim()).isEmpty())
;
name = line;
id = sf.nextLine().trim();
gpa = Double.parseDouble(sf.nextLine().trim());
// System.out.println("name: " + name + ", id: " + id + ", gpa: " + gpa);
list.add(name, id, gpa);
}
sf.close();
// commands file
File commands = new File("commands.txt");
Scanner sc = new Scanner(commands);
// output file
File output = new File("output.txt");
PrintWriter out = new PrintWriter(output);
System.out.println("*********************************************************\n"
+ "\t\tData Structures Final Report\n"
+ "******
***************************************************");
// start reading
while (sc.hasNext()) {
String command = sc.next().trim();
// System.out.println("command: " + command);
if (command.equals("TOTALSTUDENT")) {
int total = list.getTotal();
System.out.println("\nTotal number of students in the class = " + total);
} else if (command.equals("PRINTLIST")) {
System.out.println("\n************** Students List **************");
list.printList();
} else if (command.equals("ADDSTUDENT")) {
String newName = sc.nextLine();
newName = newName.trim();
String newId = sc.nextLine().trim();
Double newGpa = Double.parseDouble(sc.nextLine().trim());
System.out.println("\n************** Add Student **************");
list.addStudent(newName, newId, newGpa);
} else if (command.equals("STUDENTINFO")) {
String idToSearch = sc.next().trim();
System.out.println("\n************** Student Info **************");
list.studentInfo(idToSearch);
} else if (command.equals("DELETESTUDENT")) {
String idToDelete = sc.next().trim();
System.out.println("\n************** Delete Student **************");
list.deleteStudent(idToDelete);
} else if (command.equals("REVERSEPRINTLIST")) {
System.out.println("\n************** Reverse List **************");
list.printReverse();
} else if (command.equals("FINDLARGEST")) {
System.out.println("\n************** Highest GPA **************");
list.findLargest();
} else if (command.equals("QUIT")){
System.out.println(" ");
System.out.println("Quit");
System.out.println("*********************************************************");
}
else {
System.out.print("*********************************************************");
out.flush();
out.close();
sc.close();
sf.close();
System.exit(0);
}
}
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
}
studentlist.java class:
package classreport;
import java.io.PrintWriter;
public class StudentList {
PrintWriter out;
void setOut(PrintWriter out) {
this.out = out;
}
Node head;
Node tail;
static class Node {
Student student;
Node next;
Node prev;
Node(Student s) {
student = s;
next = null;
}
}
StudentList() {
head = null;
}
StudentList(Student student) {
head = new Node(student);
}
void printStudent (Student student){
System.out.println(student.name);
System.out.println(student.id);
System.out.println(student.gpa);
}
void addStudent (String studentName, String id, Double GPA){
Node newStudent = new Node(new Student(studentName, id, GPA));
Node helpPtr = head;
while (helpPtr != null && helpPtr.next != null) {
helpPtr = helpPtr.next;
}
if (helpPtr != null) {
helpPtr.next = newStudent;
printStudent(helpPtr.next.student);
} else
head = newStudent;
System.out.println("Student added successfully!");
}
void add (String studentName, String id, Double GPA){
Node newStudent = new Node(new Student(studentName, id, GPA));
Node temp = head;
while (temp != null && temp.next != null) {
temp = temp.next;
}
if (temp != null)
temp.next = newStudent;
else
head = newStudent;
}
int getTotal () {
// Counter for number of student.
int numStudent = 0;
// HelpPtr object for Node.
Node helpPtr = head;
// Check if head is empty or not.
if (head == null) {
// Return Counter.
return numStudent;
}
// Loop for count student.
while (helpPtr != null) {
// If helpPtr not equal to null, then increment counter.
numStudent++;
// For get next node of student.
helpPtr = helpPtr.next;
} // End loop.
// return counter.
return numStudent;
}
void studentInfo (String id){
Node helpPtr = head;
while (helpPtr != null) {
if (helpPtr.student.id.equals(id)) {
printStudent(helpPtr.student);
return;
}
helpPtr = helpPtr.next;
}
System.out.println(id + " Not found in the list");
}
public void deleteStudent (String id){
Node help_ptr = head;
if (head == null) {
if (head == tail) {
if (head.student.id.equals(id))
System.out.println(head.student.id + " Deleted!");
head = tail = null;
return;
} else if (head.student.id.equals(id)) {
// if “value” is in the first node
System.out.println(head.student.id + " Deleted!");
head = head.next;
head.prev = null;
return;
} else if (tail.student.id.equals(id)) {
// if “value” is in the last node tail = tail.prev;
System.out.println(tail.student.id + " Deleted!");
tail.next = null;
return;
} else {
while (help_ptr != null) {
if (help_ptr.student.id.equals(id)) {
System.out.println(help_ptr.student.id + " Deleted!");
help_ptr.prev.next = help_ptr.next;
help_ptr.next.prev = help_ptr.prev;
return;
}
help_ptr = help_ptr.next;
}
}
if (help_ptr == null) {
System.out.println("There is no student with id " + id + " in the system.");
return;
}
}
}
void findLargest () {
Student largestGPA = null;
Node helpPtr = head;
if (head == null) {
System.out.println("Not found in the list");
return;
}
while (helpPtr != null && head != null) {
if (largestGPA == null) {
largestGPA = helpPtr.student;
} else {
if (largestGPA.gpa < helpPtr.student.gpa) {
largestGPA = helpPtr.student;
}
}
helpPtr = helpPtr.next;
}
System.out.println("Student having highest GPA:");
printStudent(largestGPA);
}
void printList () {
Node helpPtr = head;
while (helpPtr != null && head != null) {
printStudent(helpPtr.student);
helpPtr = helpPtr.next;
}
}
public void printReverseLinkedList (Node head){
if (null == head) {
return;
}
printReverseLinkedList(head.next);
printStudent(head.student);
}
public void printReverse () {
printReverseLinkedList(head);
}
}
Student.java class:
package classreport;
public class Student {
String name;
String id;
Double gpa;
Student(String name, String id, Double gpa) {
this.name = name;
this.id = id;
this.gpa = gpa;
}
}
public void deleteStudent (String id){
Node help_ptr = head;
if (head == null) {
This condition should be
if(head!=null)
It's not allowing the rest of the code to execute
I am writing a program that stores objects of my class "TeamRecord" into a linked list. I am having issues getting the search method to work. The code below works for a linked list that only contains strings, but since this is a linked list of TeamRecord objects I need to figure out how to only look at the team name field.
calling the search method:
case 5:
System.out.println("Enter team name to search: ");
String input = console.next();
if(teams.search(input))
System.out.println(input + " is a team.");
else
System.out.println(input + " is not a team.");
break;
I get an error because String input cannot be converted to TeamRecord
Search method:
public boolean search(E element) {
if(isEmpty())
return false;
//create a new node for the element
Node<E> temp = new Node<E>(element, null);
temp = head;
while(temp != null)
{
if(temp.getElement().equals(element))
return true;
temp = temp.getNext();
}
return false;
}
I tried this:
if(teams.getTeamName().search(input))
That doesn't work though because "teams" is the name of the LinkedList so I'm not actually looking at individual objects. I'm not really sure how to approach this problem. Any help would be greatly appreciated
I will post the rest of the code here in case the above isn't enough:
public class TeamRecord implements Comparable<TeamRecord>{
private String teamName;
private int totalWin;
private int totalLoss;
public TeamRecord() {
}
public TeamRecord(String teamName, int totalWin, int totalLoss) {
this.teamName = teamName;
this.totalWin = totalWin;
this.totalLoss = totalLoss;
}
public String getTeamName() {
return teamName;
}
public void setTeamName(String teamName) {
this.teamName = teamName;
}
public int getTotalWin() {
return totalWin;
}
public void setTotalWin(int totalWin) {
this.totalWin = totalWin;
}
public int getTotalLoss() {
return totalLoss;
}
public void setTotalLoss(int totalLoss) {
this.totalLoss = totalLoss;
}
public int compareTo(TeamRecord T) {
return this.teamName.compareTo(T.teamName);
}
#Override
public String toString() {
return "\n\nTeam Name: " + teamName + "\nTotal Wins: " + totalWin +
"\nTotal Losses: " + totalLoss;
}
}
Linked List:
public class MyLinkedList<E> {
//data members
private Node<E> head;
private Node<E> tail;
int size;
//contructor
public MyLinkedList(){
head = null;
tail = null;
size = 0;
}
public boolean isEmpty(){
if(head == null)
return true;
return false;
}
public int size(){
return size;
}
public void addFirst(E element){
//create a new node for the element
Node<E> temp = new Node(element, null);
//if the list is empty
if(isEmpty()){
head = temp;
}
else{
//temp's next = head
temp.setNext(head);
head = temp;
}
size++;
}
public E removeFirst() throws EmptyListException {
if(isEmpty())
throw new EmptyListException("This list is empty.");
Node<E> temp = head;
//move head to head next
head = head.getNext();
E result = temp.getElement();
temp.setNext(null);
temp = null;
size--;
return result;
}
public void addLast(E element) {
//create a new node for the element
Node<E> temp = new Node<E>(element, null);
if(head != null)
{
Node<E> tail = head;
while(tail.getNext() != null)
{
tail = tail.getNext();
}
tail.setNext(temp);
}
else
head = temp;
size++;
}
public boolean search(E element) {
if(isEmpty())
return false;
//create a new node for the element
Node<E> temp = new Node<E>(element, null);
temp = head;
while(temp != null)
{
if(temp.getElement().equals(element))
return true;
temp = temp.getNext();
}
return false;
}
public String traverse(){
if(isEmpty())
return "Empty list";
String result = "Head --->";
int i = size;
Node<E> temp = head;
while(i > 0){
result += temp.getElement();
temp = temp.getNext();
i--;
}
return result;
}
}//end of class
Node class:
class Node<E> {
//data members
private E element;
private Node<E> next;
//constructors
public Node() {
this(null, null);
}
public Node(E element, Node<E> next) {
this.element = element;
this.next = next;
}
//setters and getters
public void setElement(E element) {
this.element = element;
}
public void setNext(Node<E> next) {
this.next = next;
}
public E getElement() {
return element;
}
public Node<E> getNext() {
return next;
}
}
Client:
public class TeamRecordClient {
static Scanner console = new Scanner(System.in);
public static int main(String [] args) {
MyLinkedList<TeamRecord> teams = new MyLinkedList();
boolean flag = true;
int userCommand;
while (flag) {
showMenu();
userCommand = console.nextInt();
switch (userCommand) {
//addFirst
case 1:
System.out.println("Enter Team Name: ");
String name = console.next();
System.out.println("Enter Total Wins: ");
int totalWins = console.nextInt();
System.out.println("Enter Total Losses: ");
int totalLosses = console.nextInt();
teams.addFirst(new TeamRecord(name, totalWins, totalLosses));
break;
//removeFirst
case 2:
try{
TeamRecord result = teams.removeFirst();
System.out.println("Removed Team: " + teams.toString());
}
catch(EmptyListException e) {
System.out.println(e.toString());
}
break;
//addLast
case 3:
System.out.println("Enter Team Name: ");
String name1 = console.next();
System.out.println("Enter Total Wins: ");
int totalWins1 = console.nextInt();
System.out.println("Enter Total Losses: ");
int totalLosses1 = console.nextInt();
teams.addLast(new TeamRecord(name1, totalWins1, totalLosses1));
break;
//traverse
case 4:
System.out.println(teams.traverse());
break;
//search for a element
case 5:
System.out.println("Enter team name to search: ");
String input = console.next();
if(teams.search(input))
System.out.println(input + " is a team.");
else
System.out.println(input + " is not a team.");
break;
case 0:
flag = false;
break;
default:
}
}//end main
}
private static void showMenu() {
System.out.print("\n\n"
+ "\n1 - Add First"
+ "\n2 - Remove First"
+ "\n3 - Add Last"
+ "\n4 - Traverse"
+ "\n5 - Search"
+ "\n6 - Selection Sort(Team Name)"
+ "\n7 - Quick Sort(Total Wins)"
+ "\n0 - Exit "
+ "\nEnter a command: ");
}
}//end of class
I suggest that you modify your search() method to take a Predicate instead:
public boolean search(Predicate<? super E> predicate) {
Node<E> temp = head;
while (temp != null) {
if (predicate.test(temp.getElement()))
return true;
temp = temp.getNext();
}
return false;
}
Then you can specify any Predicate for the search:
if (teams.search(e -> e.getTeamName().equals(input))
System.out.println(input + " is a team.");
else
System.out.println(input + " is not a team.");
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.
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.