The code can be rewritten in the following way
import java.util.Scanner;
public class UserInput
{
public static void main(String[] args)
{
//int num;
readOddNum();
//System.out.println("The odd integer is" + num);
}
public static void readOddNum()
{
int num = 0;
Scanner sc = new Scanner(System.in);
System.out.print("Enter an odd number: ");
int num1 = sc.nextInt();
sc.close();
while ((num1 < 0) ||(num1 % 2 == 0))
{
System.out.println("Wrong input!");
break;
}
System.out.println("The odd integer is" + num1);
// return readOddNum();
}
}
As you can see, I have directly called the method readOddNum();
and defined it as void
instead of the earlier version. Also, notice the changes in the while loop. You were initialising num
with 0
and using it in the while loop whereas the loop should run on num1
which is the actual user input, not num
.
Next thing is you used &&
(logical AND) instead of ||
(logical OR) and both obviously have different meanings. &&
will mean that even if user enters an even number like 2
it should also be less than 0
which isn't the case. So you need to use ||
. Also, you will need to use break to stop the loop once the statement is printed, else it will keep on executing infinitely as there's no other stopping condition. Remember that if else
has been created for scenarios like these where you have to choose between two or more situations and execute only one, so while loop will work but it will also execute the print statement, thereby stating wrong input
and odd number
. This is the output you get
C:\Java\jdk1.8.0_141\bin>java UserInput
Enter an odd number: 3
The odd integer is3
C:\Java\jdk1.8.0_141\bin>java UserInput
Enter an odd number: 2
Wrong input!
The odd integer is2
Hope you understood the concept. Appreciate it, if you like it. Thank you.