I'm wrote my code using combination of stack & queue data structures. My code is working, but I have a problem in the main()
method.
I'm using a loop to read the input from the user. The loop will break when the user enters "Exit"
.
The word "Exit"
shouldn't be pushed to the stack, but in my code it's being pushed.
I've used if
condition to break loop, but it didn't work.
My code:
public static void main(String[] args) {
StackQueue stackQueue = new StackQueue();
int dataLength = 0, i = 0;
Object data = "Start";
System.out.println("Enter data or 'Exit' to exit:");
while (!data.equals("Exit")) {
if (data.equals("Exit"))
break;
else {
data = input.nextLine();
stackQueue.enqueue(data);
dataLength ;
} // else
} // while loop
System.out.println("The entered data is: ");
while (dataLength > 0) {
System.out.println("The data no." (i = 1) ": " stackQueue.dequeue());
dataLength--;
} // while loop
}// Main Method
My output:
CodePudding user response:
The problem is that you check if the Input is "Exit" after you add it to the stack. What you can do instead is get the input and only then test it.
data = input.nextLine();
while(!data.equals("Exit")){
stackQueue.enqueue(data);
dataLength ;
data = input.nextLine();
}
One more thing is that this test
if (data.equals("Exit"))
Is not doing anything because you already checked the input in the while loop condition which is the same.
CodePudding user response:
In the code, you've listed any input provided by the user will be added to the queue. And the if input is equal to "Exit"
the condition of the while
loop will get triggered, i.e. your if
statement will never get executed.
You need to change the first while
loop by placing the break-condition right after the user input has been read and before storing the data into the queue.
To avoid redundancy, the condition of the while
loop can be set to true
because if
statement will be responsible for exiting from the loop.
// your code
while (true) {
data = input.nextLine();
if (data.equals("Exit")) break;
stackQueue.enqueue(data);
dataLength ;
}
// your code
Output with that change
A
B
C
Exit
The entered data is:
The data no.1: C
The data no.2: B
The data no.3: A
Sidenotes:
- Avoid using Object type when you know what the expected type will be, in this case,
data
has to be of typeString
; - Instead of the strict comparison with
equals()
you can useequalsIgnoreCase()
, so that both inputs "Exit" and "exit" will terminate the loop. - It's a good practice to define constant values used in the code as
public static final
variables at the top of your class. And then refer to them by name. It saves you from excremental typo (while typing the value multiple times, you can misspell it somewhere) and gives you the advantage of quick access to these constants if you need to change them because they all will be grouped together instead of being scattered all over the code.