I am facing problem with looping statement in my code, this code is for displaying even or odd numbers whatever user will input. Working fine but when I want it to ask for input next number it got failed. Explained below:
1. Console --> Please enter no:
2. User --> 25
3. console --> Even
4. console --> Do you want to continue?
5. User --> Yes
6. //Will repeat same//
7. Console -->Do you want to continue?
8. User --> No
9. //Program Should exit//
I have pasted my code here, please suggest me what to do?
Since your "oK" variable is used only once in the program, it's perfectly fine to use the literal string in place. Line 22 can be
Also, you would do well to give a better name than "scnr" -- why are you afraid of vowels? There's no prize for abbreviating variable names. There is a penalty though: "scnr" is much harder to read than "scanner". Besides, you've already declared that variable as a Scanner, why repeat yourself? A name like "userInput" conveys the purpose much better, don't you think?
Avinash Oak wrote:But can it prompt for "enter number" again after user entered a non-numeric value?
I think part of your problem is that all your code is in one place. Why not write a method that prompts the user to enter a number, keeps looping until they do, and then returns it when they finally get it right? Maybe something like:(I leave the implementation up to you ).
Then in your main() method, all you have to do is:
num = enterNumber(userInput, "Please enter no:");
Isn't it funny how there's always time and money enough to do it WRONG?