Forums Register Login

Looping through

+Pie Number of slices to send: Send
Hi,

I got the following questions as part of a basic interview test and was wondering with the second question where I'm going wrong.

Here are the questions:

QST 1: Write a function to print out user entry?

ANSWER:

QST 2: Write a function to continuously loop through the user-entered text and upon entry of “exit” by user the infinite loop exits?

ANSWER:


Basically I've got the following issues:

1 - The while loop doesnt seem to fall into an inifinite loop based on the boolean condition.

2 - I would like to confirm if my apprach of breaking out of the inifite loop is correct?

Thanks for any suggestions
+Pie Number of slices to send: Send
Your code in 2nd question is giving "Null pointer exception" at line 10. You should use scanner to read data.You can check
javadoc for explanation. Secondly dont compare booleans. You can do it like below

while(test == true) can be use as while(test) or if(outcome == true) as if (outcome)
+Pie Number of slices to send: Send
Currently you have two ways "out" of this loop.

One being the boolean variable
The other being the break statement.

You should only need one of these

either


or



Having them both there makes for confusing code.


Also, I have a pet peeve about lines that do too much.



To me this line needs breaking up to make it easier to read.
1
+Pie Number of slices to send: Send
I would have rejected any interview candidate on the spot for writing == true.
I would also have expected you to know the problems you can get with the Console class.

You can combine the reading and the test either in a do loop or a while loop like this, but you do get some strange‑looking code.
+Pie Number of slices to send: Send
Combining both the question in one answer. I have used Scanner class. Also I have used do..while loop as I wanted to print the exit message as well.

+Pie Number of slices to send: Send
I trust you don't close any other Scanners pointing to System.in.

Actually I would put my Scanners in a utility class.
What's brown and sticky? ... a stick. Or a tiny ad.
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


reply
reply
This thread has been viewed 533 times.
Similar Threads
Continious user input
How to create scrolling text?
Console Input of strings using Scanner question
Getting an Exception like NoClassDefFoundError
throwing an Exception after first exceution ..
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 02:35:45.