Friday, October 22, 2021

Writing and evaluating expressions in Java

 In this task, you are being asked to understand the evaluation order of various operators.

What are the values of the following expressions, assuming that n is 17 and m is 18? First, solve

all expressions on paper, and then write and solve in Java.

Make sure that you truly understand why and how each expression gets solved and produces

the result.

a. n / 10 + n % 10
b. n % 2 + m % 2
c. (m + n) / 2
d. (m + n) / 2.0
e. (int) (0.5 * (m + n))
f. (int) Math.round(0.5 * (m + n))

Now, crate a program called ExpressionsLab4.java, and write output statements and print both

the expression and its value.

Code: 

public class Lab4Task3{

public static void main(String[] args) {

double a, b, c, d;

int e, f, m, n;


m = 18;

n = 17;


a = n / 10 + n % 10;

b = n % 2 + m % 2;

c = (m + n) / 2;

d = (m + n) / 2.0;

e = (int) (0.5 * (m + n));

f = (int) Math.round (0.5 * (m + n));


System.out.println(a);

System.out.println(b);

System.out.println(c);

System.out.println(d);

System.out.println(e);

System.out.println(f);

}}

No comments:

Post a Comment

String Array and passing method in java

 In this task, we pass a method and also cover the passing String Array to the method. Code:   import java.util.Scanner; public class String...