11import java .util .Scanner ;
22
3- class Queue {
3+ class Queue {
44 private int [] arr ;
55 private int front ;
66 private int rear ;
@@ -74,17 +74,36 @@ public boolean isEmpty() {
7474 return rear == -1 ;
7575 }
7676
77- public boolean isFull () {
78- return rear == capacity - 1 ;
79- }
80-
81- public static void main (String [] args ) {
82- Scanner sc = new Scanner (System .in );
83-
84- System .out .print ("Enter Queue size: " );
85- int capacity = sc .nextInt ();
86-
87- Queue queue = new Queue (capacity );
77+ public boolean isFull () {
78+ return rear == capacity - 1 ;
79+ }
80+
81+ private static int readInt (Scanner sc , String prompt ) {
82+ while (true ) {
83+ System .out .print (prompt );
84+ if (sc .hasNextInt ()) {
85+ return sc .nextInt ();
86+ }
87+ System .out .println ("Invalid input. Please enter an integer." );
88+ sc .next ();
89+ }
90+ }
91+
92+ private static int readPositiveInt (Scanner sc , String prompt ) {
93+ while (true ) {
94+ int value = readInt (sc , prompt );
95+ if (value > 0 ) {
96+ return value ;
97+ }
98+ System .out .println ("Invalid input. Please enter an integer greater than 0." );
99+ }
100+ }
101+
102+ public static void main (String [] args ) {
103+ Scanner sc = new Scanner (System .in );
104+ int capacity = readPositiveInt (sc , "Enter Queue size: " );
105+
106+ Queue queue = new Queue (capacity );
88107
89108 while (true ) {
90109 System .out .println ("\n --- Queue Operations ---" );
@@ -93,18 +112,15 @@ public static void main(String[] args) {
93112 System .out .println ("3. Peek" );
94113 System .out .println ("4. Display" );
95114 System .out .println ("5. Is Full?" );
96- System .out .println ("6. Is Empty?" );
97- System .out .println ("7. Exit" );
98- System .out .print ("Enter your choice: " );
99-
100- int choice = sc .nextInt ();
101-
102- switch (choice ) {
103- case 1 :
104- System .out .print ("Enter element to Enqueue: " );
105- int element = sc .nextInt ();
106- queue .enqueue (element );
107- break ;
115+ System .out .println ("6. Is Empty?" );
116+ System .out .println ("7. Exit" );
117+ int choice = readInt (sc , "Enter your choice: " );
118+
119+ switch (choice ) {
120+ case 1 :
121+ int element = readInt (sc , "Enter element to Enqueue: " );
122+ queue .enqueue (element );
123+ break ;
108124
109125 case 2 :
110126 queue .dequeue ();
@@ -126,14 +142,14 @@ public static void main(String[] args) {
126142 System .out .println (queue .isEmpty () ? "The Queue is Empty." : "The Queue is NOT Empty." );
127143 break ;
128144
129- case 7 :
130- System .out .println ("Exiting..." );
131- sc .close ();
132- return ;
133-
134- default :
135- System .out .println ("Invalid choice! " );
136- }
137- }
138- }
139- }
145+ case 7 :
146+ System .out .println ("Exiting..." );
147+ sc .close ();
148+ return ;
149+
150+ default :
151+ System .out .println ("Invalid choice. Please enter a valid menu option. " );
152+ }
153+ }
154+ }
155+ }
0 commit comments