If and else if synatax - java

Is this
if (score >= 93)
grade = "A";
if (score >= 84 && score <= 92)
grade = "B";
if (score >= 75 && score <= 83)
grade = "C";
if (score < 75)
grade = "F";
the same as this
if (score>= 93)
grade = "A";
else if (score >= 84)
grade = "B";
else if (score >= 75)
grade = "C";
else
grade = "F";
I think they are both different because for the bottom one, if somebody has a score of 95 it is greater than 84 and 75. Which means the grade will be A, B, and C. The first if statement gives a restriction on the upper and lower bound of the score so there can be only one grade per score.

Your two pieces of code happen to produce the same result because your conditions do not overlap. Each condition is checking a specific range of values for score.
However, the following two segments of code would produce different results.
if (a > 5) {
System.out.println("a is greater than 5");
}
if (a > 3) {
System.out.println("a is greater than 3");
}
Given a=10, that code would produce: "a is greater than 5" and "a is greater than 3".
But with this code:
if (a > 5) {
System.out.println("a is greater than 5");
}
else if (a > 3) {
System.out.println("a is greater than 3");
}
Given a=10, that code would only produce: "a is greater than 5".

These logically are the same in your example.
When an if is true in an if-else block, all the subsequent elses are skipped.

The result from your two examples will be the same.
The difference in actual execution is that in your first example at least 4 and up to 6 comparisons will be made regardless of the value held in score.
In your second example as soon as an expression yields true none of the subsequent comparisons are made.

Related

How do I put a limit between the ifs?

I have a little issue, my code prints the if(RanNum >= 4) and if(RanNum >=8 ) together, but I just want to print (RanNum >=8), I want to put a limit between then, but I don't know how, thank's in advance!
int Min = 1;
int Max = 10;
int RanNum = Min + (int)(Math.random() * (Max - Min) );
System.out.println(RanNum);
if(RanNum <= 3){
System.out.println("hello");
}
if(RanNum >= 4 ){
System.out.println("four four four four four");
}
if(RanNum >= 8){
System.out.println("here it is");
}
You have an issue with your logic. For example if RanNum is greater than 8 then it will also be greater than 4. Use else if you want a branch of code that only runs when the if condition is not satisfied.
Use if else and re order the conditions
if(RanNum <= 3){
System.out.println("hello");
}else if(RanNum >= 8 ){
System.out.println("here it is");
}
else{
System.out.println("four four four four four");
}

And / or in java

im having a problem in my java exercice
the question is saying
The program will end when the sum of even is >= 50 or the sum of odd is >= 49.
so while solving it i tried to use
while (sumeven < 50 || sumodd < 49 )
and it didnt worked at all but when i checked the solution they use
while (evensum <= 50 && oddsum<=49)
and it worked ( gave same answeres like the sample run)
so my question is did i misunderstood it ? or the question have some kind of a wrong given. thank you for your time
update:
the code :
package sample2;
import java.util.Scanner;
public class Sample2 {
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
System.out.println("enter the initial value");
int sumeven=0;
int sumodd=0;
int num;
int initial;
int div5and2=0;
initial=scan.nextInt();
if (initial<=0)
System.out.println("the number must be strictly positive");
else{
if (initial%2==0)
sumeven=initial;
else
sumodd=initial;
System.out.println("start entering your numbers");
num=scan.nextInt();
if (num<=0)
System.out.println("the number must be strictly positive");
else{
while(sumeven<=50||sumodd<=49 )
{
if (num%2==0)
sumeven=sumeven+num;
else
sumodd=sumodd+num;
if (num%5==0 &&num%2==0)
div5and2=div5and2+1;
num=scan.nextInt();
while(num<=0)
{
System.out.println("the number must be strictly positive");
num=scan.nextInt();
}
}
System.out.println("the sum of even numbers: "+sumeven);
System.out.println("the sum of odd numbers: "+sumodd);
System.out.println("the number of integers divided by 2 and 5: "+div5and2);
}
}
}
}
This is basic boolean algebra.
The 'opposite' of or is and, so if you want to stop when
"even >= 50 or odd >= 49"
you have to continue on the opposite, which is
"even < 50 and odd < 49".
while(sumeven<50||sumodd<49 ) means the program will run when sumeven<50 or sumodd<49, which means it will exit when sumeven>=50 and sumodd>=49.
When you negate a statement, >= becomes < and <= becomes >. Similarly, AND becomes OR and OR becomes AND. Here, your stopping condition is even >= 50 OR odd >= 49, the negation of this (which is what is required to continue) is even<50 AND odd<49.
You want the program to end when " the sum of even is >= 50 or the sum of odd is >= 49."
So, need something like (in psuedo code):
while (Not( the sum of even is >= 50 or the sum of odd is >= 49))
De Morgan's laws tell us we need to not each part to remove the brackets and switch between and and or:
while (Not( the sum of even is >= 50) and Not( or the sum of odd is >= 49))
Let's try some examples.
If the even sum is 50 and the odd sum is 40, you want to stop.
If you check
while (sumeven < 50 || sumodd < 49 )
you will keep going since sumeven < 50 is false, but sumodd < 49 is true.
Checking both parts:
while (evensum <= 50 && oddsum<=49)
works.
while(sumeven<50||sumodd<49 )
In this case, the program did not end if sumeven<50 OR sumodd<49. That is, the program will end when sumeven>=50 AND sumodd>=50.
Boolean logic 101:
!(A || B) == !A && !B note the &&.
Essentially if you are looking at a state where either A or B and want to take the compliment of that you must code it as not either A or B which is obviously neither A nor B or not A and not B.
AIM - The program will end when the sum of even is >= 50 or the sum of odd is >= 49.
Therefore, while (sumeven < 50 || sumodd < 49 ) won't work as the program will end when the sum of even is < 50 or the sum of odd is < 49 which is not the expected behavior.
Therefore, we must loop till
The sum of even is less than or equal to 50
The sum of odd is less than or equal to 49
The overall set of conditions should only be true if all conditions are true therefore we use && operator with the 2 conditions.

Less then or equal to Else IF Java stuck

This program enters in a temperature and based on the temperature a message is outputted. My program is getting stuck tempOutside <= 50 message.. When I enter -10 the output is "Time to turn on the heat". I cannot use && as this is an assignment questions and we have not used this concept.
if (tempOutside > 50)
System.out.println("Enjoy the weather");
else if (tempOutside <= 50)
System.out.println("Time to turn on the heat");
else if (tempOutside <= 30)
System.out.println("Check the gas in you car before leaving");
else if (tempOutside <= -10)
System.out.println("BUNDLE UP it's \"COLD\" outside ");
else
1) if-else must be in numerical order (hi to low)
2) Default must be coded
3) Repeat the code, but reverse the order(low to hi)
All ints are either > 50 or <= 50. The first two conditions match everything.
Change the second condition to
> 30
And the third condition to
> -10
Etc.
it would have been more clear if you could have mentioned your exact question directly and then your implementation as it looks like there could be a misunderstanding of the question here.
But I think perhaps this is what is being asked here??
if (tempOutside > 50)
{
System.out.println("Enjoy the weather");
}
else if (tempOutside <= 50)
{
if(tempOutside <= 30)
{
if(tempOutside <= -10)
{
System.out.println("BUNDLE UP it's \"COLD\" outside ");
}
else {
System.out.println("Check the gas in you car before leaving");
}
}
else
{
//when the temp is between 30 and 50
System.out.println("Time to turn on the heat");
}
}

How do I format the logic for 3 conditions and use a previous condition as well?

NOT ASKING FOR ANYONE TO WRITE THE PROGRAM FOR ME
I am having trouble understanding how to setup the logic for a program given these following conditions:
For every day late up to and including 7 days, the late fee is $0.10/day
After 7 days, for every day late up to and including 90 days, the late fee is $0.20/day.
(Example: a book returned 10 days late incurs a late fee of $1.30 late fee, $0.10 for each of the first 7 days plus $0.20 for each of the remaining 3 days)
This is where I am having issues. I am not sure how to include the previous condition along with this one. My best guess is some sort of nested loop or an elseif containing this condition and something about the last one?
After 90 days, an unreturned book is considered lost. All late fees are waived, but the borrower is charged the cost of the book, plus a $10 restocking fee.
This is my best attempt, but I'm not sure this is the most efficient logic:
if (daysLate > 90)
{
costDue = bookPrice + 10;
}
else if (daysLate <= 90)
{
costDue = (7*0.10) * (daysLate*0.20);
}
else if (daysLate <= 7)
{
costDue = daysLate*0.10;
}
else
{
IO.reportBadInput();
}
The second condition should be changed, otherwise the third if won't be reached. Also the third condition should be changed to check if the daysLate variable is greater or equal to zero:
if (daysLate > 90)
{
costDue = bookPrice + 10;
}
else if (daysLate >= 7)
{
costDue = (7*0.10) + ((daysLate - 7) * 0.20); // change here
}
else if (daysLate >= 0)
{
costDue = daysLate*0.10;
}
else
{
IO.reportBadInput();
}
if (daysLate > 90)
{
costDue = bookPrice + 10;
}
else if (daysLate > 7 && daysLate <= 90)
{
costDue = (7*0.10) * (daysLate*0.20);
}
else
{
costDue = daysLate*0.10;
}
Simply update the second clause and drop that last one, that'll straighten it out.
addition to all previous answers - the calculation for mid-term (between 7 days and 90) should have an addition instead of multiplication (7*0.10) + (daysLate*0.20); or even 1.30 + (daysLate*0.20); (as the problem description suggests)
When you use an if statement you have to make sure that it separates the cases that you want to keep separate. In your code, the first else if statement includes all instances where daysLate <= 90, so the second else if would never execute.
Also check your past 7 days due computation, its seems like you would be overcharging people for those first 7 days.
if (daysLate > 90)
{
costDue = bookPrice + 10;
}
else if (daysLate >= 0)
{
costDue = daysLate * 0.10;
if (daysLate > 7) {
costDue += (daysLate - 7) * 0.10;
}
} else {
IO.reportBadInput();
}
Another way to do this, while sacrificing readability a bit, and eliminating one else-if condition:
if (daysLate > 90) {
costDue = bookPrice + 10;
}
else if (daysLate >= 0 && daysLate <= 90) {
costDue = Math.min(7, daysLate) * 0.10 + Math.max(daysLate - 7, 0) * 0.20;
}
else {
IO.reportBadInput();
}

Picking the smallest and biggest numbers of a list without any methods

Im trying to pick from a list of 5 numbers, the biggest and the smallest numbers.
With the biggest I have no problems, either with the smallest for some cases.
But, for the smallest number I would like to adding a condition that if its zero ('0'), I wouldn't pick it, thats mean from 5 numbers I would like to pick the smallest one, that is not 0.
for example:
1000 2000 3000 0 0
I would like to pick the 1000.
Also, I can't use any methods, or based functions, Just If statements.
thats my code:
if((manufactorsPrice1<manufactorsPrice2)&&(manufactorsPrice1<manufactorsPrice3)&&(manufactorsPrice1<manufactorsPrice4)&&(manufactorsPrice1<manufactorsPrice5)){
if(manufactorsPrice1>0){
smallestPrice=manufactorsPrice1;
}
}else if((manufactorsPrice2<manufactorsPrice3)&&(manufactorsPrice2<manufactorsPrice4)&&(manufactorsPrice2<manufactorsPrice5)){
if(manufactorsPrice2>0){
smallestPrice=manufactorsPrice2;
}
}else if((manufactorsPrice3<manufactorsPrice4)&&(manufactorsPrice3<manufactorsPrice5)){
if(manufactorsPrice3>0){
smallestPrice=manufactorsPrice3;
}
}else if(manufactorsPrice4 < manufactorsPrice5){
if(manufactorsPrice4>0){
smallestPrice=manufactorsPrice4;
}
}else{
if(manufactorsPrice5>0){
smallestPrice=manufactorsPrice5;
}}
Thats work fine if I could pick the 0 as the smallest, But I cannot. Please help me, How can I pick the next smallest number that is not a Zero from the list.?
thanks.
Here is a solution which only uses an extra local variable to reduce nesting. It will find the minimum non-zero value (if it exists) or zero in the case they are all 0. It also uses fewer comparisons.
...
int min1, min2;
if (a2 == 0 || (a1 < a2 && a1 != 0))
min1 = a1;
else
min1 = a2;
if (a4 == 0 || (a3 < a4 && a3 != 0))
min2 = a3;
else
min2 = a4;
if (min1 == 0 || (min2 < min1 && min2 != 0))
min1 = min2;
if (min1 == 0 || (a5 < min1 && a5 != 0))
min1 = a5;
return min1;
Solution appropriate for your teacher who only allows the use of conditionals...
s=
(s=
(s=
(s=
x2!=0&&x2
<x1?x2:x1)>x3
&&x3!=0?x3:s)>x4
&&x4!=0?x4:s)>x5
&&x5!=0?x5:s;

Categories