Welcome to the CSC Q&A, where you can get help (and share your knowledge) about computer science!

Has anyone gotten to or already know about the if...then statements?

+7 votes
How would I say, "if *what user types in* is not integer, then display message"?
asked Sep 6, 2016 in CSC 211 (F16) by Brandon Wilkerson (100 points)

3 Answers

+4 votes

I think Minh is on the right track. Here's one way

if ( x != (int)x ) {

        System.out.print("your message");


Here's another way

if (x == (int)x) {

        System.out.print("x is an integer");


else {

        System.out.print("<your message>");


/* I hope it's legal to share code like this when somebody asks a generic question! Forrest? */

answered Sep 7, 2016 by Jon Clauss (100 points)
Yes, absolutely!  My general rules are:  DON'T share any source code for exercises or labs.  You MAY post source code for self-checks (where the answers are available anyway) or source code that answers generic/extra questions.  For projects, if there's a tiny part of your project code that isn't working, you may post a a tiny bit of the code up on the Q&A in order to ask a question about it, but you should not post much project code.  It would be better to ask/talk about a similar situation to the project, without dealing with the specific project code.
+3 votes

There's no if - then in Java, but there;s a if - else statement basically because if itself is if - then.

What you can do to resolve your problem is to declare a variable, type in the number and then use the expression != to show your "is not". So if (a != b) is if a is not equal to b then do the following statement.

A smart way to do to distinguish a double from a variable is to do if ( a != (int) a).


answered Sep 7, 2016 by Minh Ta (100 points)
+1 vote

While Jon & Minh have some good info in their answer, it sounds like what you're specifically asking about is how to do error handling when you want someone to type in a number, but they type in something else instead (like the string of text "five").

If that's the case, then it's a bit too late to check after you've already gotten the value, because Java will throw a runtime error during the line if the user didn't type an int.

x = console.nextInt();

So you'd actually have to do something like this:

if (console.hasNextInt()) {
    x = console.nextInt();

This is all getting pretty far ahead of where we are now though.  If you'd like to know more about this, feel free to jump ahead and look at Chapter 5 Section 4 of our textbook...

answered Sep 11, 2016 by Forrest Stonedahl (100 points)