• Post Reply Bookmark Topic Watch Topic
  • New Topic

Looping through  RSS feed

 
Alex Monari
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Tushar Goel
Ranch Hand
Posts: 934
4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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)
 
Stefan Evans
Bartender
Posts: 1837
10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Campbell Ritchie
Marshal
Posts: 56600
172
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Karthick Pattabiraman
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

 
Campbell Ritchie
Marshal
Posts: 56600
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I trust you don't close any other Scanners pointing to System.in.

Actually I would put my Scanners in a utility class.
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!