PDA

View Full Version : Why does this happen?


albear
Oct 14, 2007, 12:20 PM
when I input a number that is less than -5 it prints off 'this number is valid' and 'this number is invalid'
I know its because of where its placed but how can I prevent it so that it only brings up one message.

import java.util.*; // the package containing Scanner
public class Ranges
{
public static void main(String[] args)
{

Scanner kybd = new Scanner(System.in);

//input

System.out.println("Enter an integer");
int Num1;
Num1 = kybd.nextInt();

//calculations and output

if (Num1 < -5)
{
System.out.println("Number is valid");
}

if ( (Num1 >= 4)&&(Num1 <= 12))
{
System.out.println("Number is valid");
}
else
{
System.out.println("Number is invalid");
}
}
}

albear
Oct 14, 2007, 12:42 PM
Any ideas...

retsoksirhc
Oct 14, 2007, 12:51 PM
I don't work with java, but I can see the control flow of the program. You need to use an elseif instead of an if for the seconf condition.
if ( (Num1 >= 4)&&(Num1 <= 12))
it's got one if, but then instead of doing an ELSE if, it just goes to a second if, and then when it gets to the else, it goes through it because the integer didn't meet the requirements for the second if, even though it may have for the first.

It usually helps to do indenting, so you can see exactly where one block of IF statements starts and stop, and the next starts.

albear
Oct 14, 2007, 12:58 PM
I tried replacing my second 'if' with 'elseif', but it doesn't like that I tried putting brackets around both 'if' statements but it didn't like either of them (separetly), thanks

retsoksirhc
Oct 14, 2007, 01:11 PM
I just looked up the syntax, it's actually else if, not elseif (two words)
Try this:


if (Num1 < -5)
{
System.out.println("Number is valid");
}

else if ( (Num1 >= 4)&&(Num1 <= 12))
{
System.out.println("Number is valid");
}
else
{
System.out.println("Number is invalid");
}

albear
Oct 14, 2007, 01:15 PM
Yes it works thank you mr koster

retsoksirhc
Oct 14, 2007, 01:20 PM
yes it works thankyou mr koster
No problem. And might I say, that first quote in your signature is pretty awesome. The Gary Jules cover of the song is much better, in my opinion.

albear
Oct 14, 2007, 01:22 PM
No problem. And might I say, that first quote in your signature is pretty awesome. The Gary Jules cover of the song is much better, in my opinion.
Agreed it is rather cool,