I need to write out a boolean statement that prints 'true' if the number entered (using scanner input) is...
- within a range of 1 to 100 but NOT an even number within the range 40 to 50.
As in, if the user inputs something like 44 or 46, the output will return 'false' but if it is 45 or 43, it should return 'true'. If it's a number below 40 but less than 1, output should be 'true'. If it's a number above 50 but less than 100, output should be true as well.
this is what I have so far..
int testValue1;
System.out.println("enter number");
Scanner scan = new Scanner(System.in);
testValue1 = scan.nextInt();
scan.close();
int low = 40, high = 50;
int min = 1, max = 100;
boolean a = true;
boolean b = false;
if ( testValue1>=min && testValue1<=max && (testValue1 >= low && testValue1 <= high && testValue1 % 2 == 1)) {
System.out.println(a);
} else {
System.out.println(b);
}
}
- This one returns 'false' for every number except if it's an odd number within 40 to 50. So if I enter 45 I get true, but if I enter any number that's lower than 40 or higher than 50 I get false...
please help I'm completely new to programming and don't know what I'm doing...
CodePudding user response:
when people say if they usually mean if and only if when you write if in a programming language it just means if
CodePudding user response:
This is not a difficult problem. Read the conditions carefully and work it out on paper (if neccesary) before writing code.
int number ;
Scanner scan = new Scanner(System.in) ;
System.out.println("Enter a number") ;
number = scan.nextInt() ;
if (number >= 1 && number <= 100) { // check if the entry is within the range 1 to 100 inclusive
if (number >= 40 && number <= 50) { // check if it's between 40 and 50
if (number % 2 != 0) { // if it's odd
System.out.println("true") ;
}
else {
System.out.println("false") ;
}
}
else {
System.out.println("true"); // happens only if number is between 1 to 39 inclusive and 51 to 100 inclusive
}
}
else {
System.out.println("false") ; // occurs when number is less than 1 or more than 100
}
CodePudding user response:
You need to simplify your thinking.
System.out.println("enter number");
Scanner scan = new Scanner(System.in);
int number = scan.nextInt();
scan.close();
//make sure it is within the range of 0 and 100
if (number >= 0 && number <= 100) {
//check if it is between 40 and 50
if (number >= 40 && number <= 50) {
//check if it is odd (remainder should be 1 if so)
if (number % 2 == 1) {
//number is odd so print true
System.out.println(true);
} else {
//number is even and between 40-50 print false
System.out.println(false);
}
} else {
//number is between 0 and 100
//number is not between 40 and 50
System.out.println(true);
}
} else {
//number is not between 0 and 100
System.out.println(false);
}
}