• Post Reply Bookmark Topic Watch Topic
  • New Topic

tie IF statement into do while loop  RSS feed

 
Mike Philips
Ranch Hand
Posts: 56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a do while loop that's just asking the user to input a number until the number 6 is input, at which point the user gets congratulated for entering the number 6...


however I'd like to make an if statement that changed the SystemOutput if an incorrect value was entered. If a letter is entered at the moment the program returns an error, so I was wondering how to make it so that if letters are entered instead of numbers the program will return something along the lines of asking the user to enter a number instead, and re prompting for a number...

I'm not sure where the If statement should live, inside the do code block or after it where the while part is?

Also, I'm not sure how I'm meant to write the if statement. If i try " if(ScannerInput != int) I get an error. I guess I can't use the int variable in this context...

Hope that makes some sense. Thanks!
 
Anayonkar Shivalkar
Bartender
Posts: 1558
5
Eclipse IDE Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Welcome to CodeRanch!

What you've mentioned is a common requirement, and can be done.

However, can you please TellTheDetails - that is, what is your code (at least the do-while loop) and what error you are getting (are you sure it is error, and not exception?)
 
Mike Philips
Ranch Hand
Posts: 56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Anayonkar , sorry I didn't post code... Here it is though :




I know that the IF returns errors at the moment but hopefully the intention of it is fairly clear!

Thanks.
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 37462
537
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That if statement isn't in the main method let alone a while loop. Where do you think the while loop should go?
 
Mike Philips
Ranch Hand
Posts: 56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ah no! sorry about that

 
Henri Melissimo
Greenhorn
Posts: 3
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A few things about the code:
-Avoid using 'Character' as a variable name on line 14.
-Not sure what you are trying to do on line 21, where you compare a variable to a Java primitive type keyword.
I suspect you want to check if the value read from the scanner is of the int type (alphanumeric maybe?). The way I would do it is as follow:
+Line 14: short x = input.nextShort();
+Line 21: if(Character.isAlphabetic(x)) { /* add some code here*/ };
There might be some more elegant ways to do it. But you can check the methods on the Character class for some validation of the input you just read in.

Hope it help.
 
Campbell Ritchie
Marshal
Posts: 56525
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch
 
Mike Philips
Ranch Hand
Posts: 56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A few things about the code:
-Avoid using 'Character' as a variable name on line 14.


Are you referring to the same code? I know that I posted the wrong one first...

cheers though
 
Campbell Ritchie
Marshal
Posts: 56525
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because of obscuring, you can get all sorts of subtle errors, and they can be difficult to correct. There are good reasons for the naming conventions; for a start following them strictly will completely prevent obscuring. If you have a variable called Character in scope, you cannot use the Character class normally
 
Red Smith
Ranch Hand
Posts: 136
1
Netscape Opera Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Mike Philips wrote:I have a do while loop that's just asking the user to input a number until the number 6 is input, at which point the user gets congratulated for entering the number 6...


however I'd like to make an if statement that changed the SystemOutput if an incorrect value was entered. If a letter is entered at the moment the program returns an error, so I was wondering how to make it so that if letters are entered instead of numbers the program will return something along the lines of asking the user to enter a number instead, and re prompting for a number...

I'm not sure where the If statement should live, inside the do code block or after it where the while part is?


The nextInt() method throws an exception if it doesn't find a number as the next token in the input. So you should call it in a try block and catch InputMismatchException . However, in doing that just now, it seems like the bad characters just remain in the scanner and have to be removed in order for nextInt() to work. Calling nextLine() got me past the alpha chars, but it seems like there should be a better way to do that.
 
Mike Philips
Ranch Hand
Posts: 56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Red wrote: The nextInt() method throws an exception if it doesn't find a number as the next token in the input. So you should call it in a try block and catch InputMismatchException . However, in doing that just now, it seems like the bad characters just remain in the scanner and have to be removed in order for nextInt() to work. Calling nextLine() got me past the alpha chars, but it seems like there should be a better way to do that.


Cheers Red, that went over my head a bit to be honest, probably a few thing's I need to get through first ;)

Campbell wrote: Because of obscuring, you can get all sorts of subtle errors, and they can be difficult to correct. There are good reasons for the naming conventions; for a start following them strictly will completely prevent obscuring. If you have a variable called Character in scope, you cannot use the Character class normally


Thanks Campbell I'll have a look at the link... Using reserved names as variables is bad practice !

 
Campbell Ritchie
Marshal
Posts: 56525
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You never need catch an Exception from a Scanner, because as Rob Spoor pointed out, you can always avoid those Exceptions. The trick with the loop may not work if you have a file whose structure is closely bound to the program, but it should work from the keyboard where the user can see the error messages. I think that sort of code belongs in a static method in a utility class. Call it KeyboardInputs or similar.
 
Red Smith
Ranch Hand
Posts: 136
1
Netscape Opera Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Mike Philips wrote:

Cheers Red, that went over my head a bit to be honest, probably a few thing's I need to get through first ;)




It would look like this:

 
Mike Philips
Ranch Hand
Posts: 56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
cheers for the replies, answers are still a bit over my head though, I'm still learning for loops etc... thanks though!
 
Jj Taylor
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm learning 2D applet game programming which isnt my ambition but its making me learn for loops & while a lot easier and a better understand why you'd use them on other real world applications. Mainly covers the basics as there simple games but worth a shot.
 
Mike Philips
Ranch Hand
Posts: 56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jj Taylor wrote:I'm learning 2D applet game programming which isnt my ambition but its making me learn for loops & while a lot easier and a better understand why you'd use them on other real world applications. Mainly covers the basics as there simple games but worth a shot.


Cheers Jj, I'm currently writing something that asks the user for their name then returns it! Just to give you an idea of where I'm at ;)
 
Campbell Ritchie
Marshal
Posts: 56525
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A lot of people regard applets as obsolete and as a security hazard.
 
Campbell Ritchie
Marshal
Posts: 56525
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Mike Philips wrote: . . . Using reserved names as variables is bad practice !
Didn't notice that post earlier.

You can use reserved words as variables as much as you like, and nothing can go wrong … because it won't compile! Character isn't a reserved word, but a legal identifier. That is why it can cause confusion. The compiler will happily accept it without noticing it has already been used.
 
Campbell Ritchie
Marshal
Posts: 56525
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Red Smith wrote: . . . It would look like this: . . .
didn't notice that on Friday, but you shouldn't catch Exceptions from a Scanner. Look at the links I posted a minute before that; you can always avoid such exceptions from Scanner. Look at that link, and the older links in it.
There are two big differences between reading from a file and keyboard (System.in):-
  • You must always close a Scanner pointing at a file and therefore need to check whether it is closed. You must never close a Scanner pointing to System.in.
  • If you have incorrect input from System.in, the user can see the error message and provide new input. You can't do that for a file, but the program and the file need to match each other.
  • Beware of nextLine(). It does not do what you think it does. I never realised there were that many spelling errrors in that last link
     
    Mike Philips
    Ranch Hand
    Posts: 56
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Campbell Ritchie wrote:
    Mike Philips wrote: . . . Using reserved names as variables is bad practice !
    Didn't notice that post earlier.

    You can use reserved words as variables as much as you like, and nothing can go wrong … because it won't compile! Character isn't a reserved word, but a legal identifier. That is why it can cause confusion. The compiler will happily accept it without noticing it has already been used.


    Ha, is not compiling an acceptable thing? To me it sound's like something I wouldn't want...
     
    Mike Philips
    Ranch Hand
    Posts: 56
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Campbell Ritchie wrote:
    Red Smith wrote: . . . It would look like this: . . .
    didn't notice that on Friday, but you shouldn't catch Exceptions from a Scanner. Look at the links I posted a minute before that; you can always avoid such exceptions from Scanner. Look at that link, and the older links in it.
    There are two big differences between reading from a file and keyboard (System.in):-
  • You must always close a Scanner pointing at a file and therefore need to check whether it is closed. You must never close a Scanner pointing to System.in.
  • If you have incorrect input from System.in, the user can see the error message and provide new input. You can't do that for a file, but the program and the file need to match each other.
  • Beware of nextLine(). It does not do what you think it does. I never realised there were that many spelling errrors in that last link


    I'm not sure what I'm meant to be taking from that thread about getter/setter... I've not encountered these terms yet.

    I don't know why I should beware of nextLine(); at the moment... or what I should be using as an alternative.

    Is next line not working for that guy's code because the next line after the command was an integer rather than a String? Are you not meant to mix Integers and Strings within the same array / scanner? I don't understand the solution



    so he's meant to include that into the section




    so that it looks like






    I still don't understand what is to be weary of about nextLine() - it kind of looks like nextInt() is corrected using nextLine() in this example... Although there's (obviously) something that I'm missing here.

    Does s.nextInt() not refer to the next integer input via the Scanners System.in?

    I realise that I'm asking a lot of questions, I feel I gave fair warning as to my level though! ;)
     
    Mike Philips
    Ranch Hand
    Posts: 56
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Campbell Ritchie wrote: You must never close a Scanner pointing to System.in.


    really? I have read that I'm meant to close scanners elsewhere - and Eclipse flags a little exclamation if I don't...

    Why shouldn't I close the scanner?
     
    Campbell Ritchie
    Marshal
    Posts: 56525
    172
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Mike Philips wrote: . . . Why shouldn't I close the scanner?
    Try it and find out.Or read this recent thread.
     
    Campbell Ritchie
    Marshal
    Posts: 56525
    172
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Mike Philips wrote: . . .
    I'm not sure what I'm meant to be taking from that thread about getter/setter... I've not encountered these terms yet.
    I am a bit surprised you haven't come across getters and setters; maybe you have heard them called accessor and mutator methods. The thread I quoted was about two problems. One was that the questioner was not using get methods correctly. The other was the confusion about nextLine which appeared to be putting all the inputs out of phase with one another. I was trying to warn you about nextLine because that particular problem is badly described in most books.

    . . .
    Is next line not working for that guy's code because the next line after the command was an integer rather than a String? . . .
    No, that problem is independent of the type of input. If you call nextXXX and write the input, nothing happens. If you push the enter key, the input is fed to the Scanner, but there is a risk of nextLine picking up an empty String. In that example nextInt was called, and the number read, and it was followed immediately by nextLine, which read the empty String. Then it attempted to read the subsequent line as a number, causing an Exception.
    Possible solution: nextLine twice, discarding the first result. Better solution (maybe):-In my opinion, keyboard reading code should be put into a utility class. Then you can call
    i = KeyboardInputs.getInt("Please enter number for ...");
    and use that class again and again.
    I realise that I'm asking a lot of questions, I feel I gave fair warning as to my level though! ;)
    The more questions you ask the more you learn.
     
    Campbell Ritchie
    Marshal
    Posts: 56525
    172
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Mike Philips wrote: . . . I have read that I'm meant to close scanners elsewhere . . .
    Close Scanners, Readers, Writers, Formatters, etc, everywhere except System.in, System.out and System.err.
     
    Campbell Ritchie
    Marshal
    Posts: 56525
    172
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Details of the trim method here, and the isEmpty() method (correct spelling!).
     
    Mike Philips
    Ranch Hand
    Posts: 56
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Campbell Ritchie wrote:
    If you call nextXXX and write the input, nothing happens. If you push the enter key, the input is fed to the Scanner, but there is a risk of nextLine picking up an empty String


    Would this happen because the user entered "1515 " (white space at the end) instead of "1515" ?



    In that example nextInt was called, and the number read, and it was followed immediately by nextLine, which read the empty String. Then it attempted to read the subsequent line as a number, causing an Exception


    I'm struggling to really follow along that code - but you say immediately after :



    Are you referring to the part?

    or the



    part?



    I am a bit surprised you haven't come across getters and setters; maybe you have heard them called accessor and mutator methods.


    Nope, haven't come across any of these, which is why I warned as I don't want to waste everyone's time trying to learn thing's if they're too far down the road for me at the moment :/ I'm just following along these tutorials at the mo https://www.udemy.com/java-tutorial


    In my opinion, keyboard reading code should be put into a utility class. Then you can call
    i = KeyboardInputs.getInt("Please enter number for ...");
    and use that class again and again.


    So is that a class? Should I make that class? Or this is an 'in an ideal world' kind of thing?



    Close Scanners, Readers, Writers, Formatters, etc, everywhere except System.in, System.out and System.err.


    OK just so that I'm clear on this (because Eclipse flags it as an error if I don't close it) I was incorrect to close the scanner class in the 5th post of this thread? I should just leave nothing at the end?
     
    Campbell Ritchie
    Marshal
    Posts: 56525
    172
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Mike Philips wrote: . . . Would this happen because the user entered "1515 " (white space at the end) instead of "1515" ?
    . . .
    No, it has to do with the way nextLine works. You think it reads the next line, but it doesn't. It reads the remainder of the current line.

    I can't remember which bit of the program about record labels I was referring to.
    . . .
    Nope, haven't come across any of these [setters and getters], . . .
    I am still surprised, because I came across setters and getters (only under their posh names) within the first two weeks I was learning Java®.
    So is that a class? Should I make that class? Or this is an 'in an ideal world' kind of thing?
    It is something you will probably do in a few weeks when you have a bit more experience.
    OK just so that I'm clear on this (because Eclipse flags it as an error if I don't close it) I was incorrect to close the scanner class in the 5th post of this thread? I should just leave nothing at the end?
    Yes, leave the Scanner to go out of scope.
    When you write yourself a utility class, you can use one Scanner object and one only, and leave it until the JVM exits.

    As for the inputs, try this, with the following inputs:-
  • 123 456 789 Campbell Ritchie 987
  • 123 456 789
        Campbell Ritchie
        987
  • In one case name will be empty or all spaces and it will try to convert "Campbell" to an int and throw an Exception.
     
    • Post Reply Bookmark Topic Watch Topic
    • New Topic
    Boost this thread!