Java exercises and solutions: singly linked list menu


Java OOP: singly linked list

Singly linked list menu

Step 6: Display a menu of choices

To show the menu that allow the user to choose an operation on the linked list, you need the showmenu() and select() functions as shown below:

// display a menu of choices

public static void showmenu(){

System.out.println("=================================");
System.out.println("Linked List Operations Menu");
System.out.println("=================================");
System.out.println("1.Add a new item");
System.out.println("2.Delete an item");
System.out.println("3.Show number of items");
System.out.println("4.Show all items");
System.out.println("5.Exit");

}

public static void select(){

SLinkedList<Integer> mylist=new SLinkedList<Integer>();
int val, pos, ch,yes=0;
Scanner sc=new Scanner(System.in);
try{
while(yes==0){
System.out.print("Enter your choice:");
ch=sc.nextInt();
switch(ch){
case 1:
System.out.print("Value:");
val=sc.nextInt();
System.out.print("Position:");pos=sc.nextInt();
mylist.insert(val,pos);
break;
case 2:
System.out.print("Position:");pos=sc.nextInt();

mylist.delete(pos);
break;
case 3:
System.out.println("Number of items:"+mylist.countitem());
break;
case 4:
System.out.println("All items:");
mylist.printall();
break;
case 5: System.exit(0);

default: System.out.println("Invalid choice!");

}


System.out.print("Continue? Press 0 to continue:");
yes=sc.nextInt();

}

}catch(Exception e){System.exit(100);}

}




Comments




This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.