0% found this document useful (0 votes)
11 views9 pages

Java Practice: Triangle Area & Formulas

The document provides Java programming exercises that include calculating the area of a triangle, implementing various mathematical formulas, determining the number of buses needed for a field trip, and evaluating boolean expressions. It also discusses incorrect variable declarations and conventions in Java programming. Each section includes code examples and explanations for the exercises.

Uploaded by

harilavgs
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views9 pages

Java Practice: Triangle Area & Formulas

The document provides Java programming exercises that include calculating the area of a triangle, implementing various mathematical formulas, determining the number of buses needed for a field trip, and evaluating boolean expressions. It also discusses incorrect variable declarations and conventions in Java programming. Each section includes code examples and explanations for the exercises.

Uploaded by

harilavgs
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

CSA0961-JAVA

PRACTICE- 4.2

1. Write a program that will take in the base and height of a triangle and calculate and display

the area of the triangle using the formula below. 𝐴𝐴 = 1 2 𝑏𝑏ℎ

CODE:

import [Link];

public class TriangleArea

public static void main(String[] args)

Scanner scanner = new Scanner([Link]);

[Link]("Enter the base of the triangle: ");

double base = [Link]();

[Link]("Enter the height of the triangle: ");

double height = [Link]();

double area = 0.5 * base * height;

[Link]("The area of the triangle is: " + area);

}
2. Write the following math formulas in Java. You will need to use methods from the Math

class as well as nesting of methods and parentheses to force the order of operations to

correctly calculate the answer. Assume that all the variables in the formulas have already

been declared and initialized.

a. 𝑎𝑎 = √𝑥𝑥5−6 4

b. 𝑏𝑏 = 𝑥𝑥𝑦𝑦 − 6𝑥𝑥

c. 𝑐𝑐 = 4𝑐𝑐𝑐𝑐𝑐𝑐( 𝑧𝑧 5 ) − 𝑠𝑠𝑠𝑠𝑠𝑠𝑥𝑥2

d. 𝑑𝑑 = 𝑥𝑥4 − �6𝑥𝑥 − 𝑦𝑦3

e. 𝑒𝑒 = 1 𝑦𝑦− 1 𝑥𝑥−2𝑦𝑦

f. 𝑓𝑓 = 7(𝑐𝑐𝑐𝑐𝑐𝑐(�5 − 𝑠𝑠𝑠𝑠𝑠𝑠√3𝑥𝑥 − 4))

code:

public class MathFormulas {

public static void main(String[] args) {

if ([Link] < 3) {

[Link]("Please provide the values for x, y, and z as arguments.");


return;

double x = [Link](args[0]);

double y = [Link](args[1]);

double z = [Link](args[2]);

// a = √(x^5 - 6) / 4

double a = [Link]([Link](x, 5) - 6) / 4;

// b = xy - 6x

double b = x * y - 6 * x;

// c = 4cos(z / 5) - sin(x^2)

double c = 4 * [Link](z / 5) - [Link]([Link](x, 2));

// d = x^4 - √(6x - y^3)

double d = [Link](x, 4) - [Link](6 * x - [Link](y, 3));

// e = 1 / (y - 1 / (x - 2y))

double e = 1 / (y - 1 / (x - 2 * y));

// f = 7 * cos(√(5 - sin(√(3x - 4))))

double f = 7 * [Link]([Link](5 - [Link]([Link](3 * x - 4))));

[Link]("a = " + a);


[Link]("b = " + b);

[Link]("c = " + c);

[Link]("d = " + d);

[Link]("e = " + e);

[Link]("f = " + f);

[Link] holds 45 people. The school will only use a bus if they can fill it completely. The rest of the

people will ride in vans. Write a program that will take in the number of people that are signed

up to go on a field trip. Have the program print the number of busses necessary and then total

number of people that will need to ride in vans.


Code:

public class FieldTrip {

public static void main(String[] args) {

if ([Link] < 1) {

[Link]("Please provide the number of people signed up for the field trip

as an argument.");

return;

int people = [Link](args[0]);

int busCapacity = 45;

int busesNeeded = people / busCapacity;

int peopleInVans = people % busCapacity;

[Link]("Number of buses needed: " + busesNeeded);

[Link]("Number of people that will need to ride in vans: " + peopleInVans);

}
4. 4. Write true or false on the blanks in the program below to show the value of the boolean

variable true_false as the program executes.

Code:

public class TrueFalse {

public static void main(String[] args) {

int i = 5;

int j = 6;

boolean true_false;

true_false = (j < 5); // false


[Link](true_false);

true_false = (j > 3); // true

[Link](true_false);

true_false = (j < i); // false

[Link](true_false);

true_false = (i < 5); // false

[Link](true_false);

true_false = (j <= 5); // false

[Link](true_false);

true_false = (6 < 6); // false

[Link](true_false);

true_false = (i != j); // true

[Link](true_false);

true_false = (i == j || i < 50); // true

[Link](true_false);

true_false = (i == j && i < 50); // false

[Link](true_false);

true_false = (i > j || true_false && j >= 4); // true

[Link](true_false);

true_false = (!(i < 2 && j == 5)); // true

[Link](true_false);

true_false = !true_false; // false

[Link](true_false);

}
5. 5. Explain why each of the declarations in the second list are wrong.

[Link] gameOver = false;

int students=50,classes=3;

double sales_tax;

short number1;

2. int 2beOrNot2be;

float price index;

double lastYear'sPrice;

long class;

ANS:

 int 2beOrNot2be;

 Variable names cannot start with a digit.


 float price index;

 Variable names cannot contain spaces.

 double lastYear'sPrice;

 Variable names cannot contain apostrophes.

 long class;

 class is a reserved keyword in Java and cannot be used as a variable name.

6. Explain Why Declarations Do Not Follow Conventions

1. int cadence=3, speed=55, gear=4;

o Multiple variables should be declared on separate lines for readability.

2. final double SALES_TAX=.06;

o Constants should be in uppercase, but underscores should be used to separate

words for readability (e.g., SALES_TAX).

3. double gearRatio=.5;

o Mixed case is acceptable, but the Java convention is to use camelCase (e.g.,

gearRatio).

4. int currentGear=5;

o This follows conventions.

5. int c=3, s=55, g=4;

o Variable names should be descriptive (e.g., cadence, speed, gear).

6. final double salesTax=.06;

o Constants should be in uppercase and use underscores to separate words (e.g.,

SALES_TAX).

7. double gearrat

o Variable names should use camelCase and be descriptive (e.g., gearRatio).

Common questions

Powered by AI

The Java programs handle errors by checking if the expected arguments are present using conditional statements. If the required arguments are not provided, the program immediately outputs an error message and exits, preventing further execution. For example, in the FieldTrip program, 'if (args.length < 1)' checks for the presence of the required number of arguments and halts the program with a message if they're missing. This form of error detection helps prevent runtime errors that arise from incorrect or incomplete user input .

The TrueFalse Java program illustrates boolean logic by assigning boolean expressions to the variable 'true_false' and then printing its value. Evaluations such as '(j < 5)', which results in false since j=6, and '(j > 3)', which is true, demonstrate how conditions are processed. Logical operators like && and || are used in expressions such as '(i == j || i < 50)', where the latter condition makes the expression true. This program thus showcases a variety of true and false conclusions drawn from different logical conditions .

To follow Java naming conventions, developers should declare variables on separate lines for readability, use camelCase for variable names like gearRatio, and ensure that constant names are in uppercase with underscore separators such as SALES_TAX. Also, variable names should be descriptive rather than single letters, e.g., using cadence instead of c. Following these conventions increases code maintainability and readability .

Several variable declarations in Java are incorrect due to violations of naming rules and conventions: 'int 2beOrNot2be;' is incorrect because variable names cannot start with a digit. 'float price index;' is invalid because variable names cannot contain spaces. 'double lastYear'sPrice;' is incorrect due to the use of an apostrophe, which is not allowed. Lastly, 'long class;' fails because 'class' is a reserved keyword in Java and cannot be used as a variable name .

Java's Math class provides methods such as Math.sqrt() for square root and Math.pow() for exponentiation, which allow developers to accurately calculate the given formula. Specifically, using Math.pow(x, 5) computes \( x^5 \), and Math.sqrt(...) calculates the square root of the expression \( x^5 - 6 \). These values are then divided by 4. The calculation in Java would look like: double a = Math.sqrt(Math.pow(x, 5) - 6) / 4 .

Parentheses play a critical role in enforcing the desired order of operations in Java expressions, especially when using Math class functions. They override the default precedence of operations, ensuring that nested calculations such as Math.sqrt(), Math.pow(), and arithmetic are performed in the intended sequence. For example, in the expression 'Math.sqrt(Math.pow(x, 5) - 6) / 4', parentheses ensure that the exponentiation \( x^5 \) occurs before the subtraction and square root operations, thereby preventing errors in order of evaluation in complex expressions .

Handling edge cases in Java's Math class requires understanding how operations behave towards invalid inputs. For instance, Math.sqrt() will return NaN (Not-a-Number) if given a negative input, since the square root of a negative number is undefined in real numbers. Similarly, division operations need to handle zero denominators carefully; Java will throw an ArithmeticException if a division by zero is attempted with integers, although operations like 1.0/0 would yield Infinity with floating-point numbers. Consideration for such edge cases is crucial to writing robust programs .

The logic for determining bus and van usage in a field trip scenario is based on integer division and modulus operations. Given the total number of people, the program first calculates the number of buses needed by dividing the total number of people by the bus capacity (45) using integer division. This ensures only full buses are considered: int busesNeeded = people / busCapacity. To find how many people need to use vans, the modulus operator is used: int peopleInVans = people % busCapacity; this gives the remainder of people not accommodated by full buses. This effectively distributes people such that only full buses and necessary vans are used .

Grouping multiple variable declarations on a single line can make the code concise and reduce the total line count, which might be beneficial for short scripts. However, this practice can lead to reduced readability, especially in complex programs, making it harder to track variable initialization and types. It becomes more challenging for others to understand or modify the code quickly. On the other hand, declaring each variable on a separate line enhances readability, allowing for clear documentation and individual commenting, which benefits debugging and maintenance .

To optimize Boolean logic expressions in Java, one should simplify conditions by eliminating redundant comparisons and using De Morgan's laws to transform negations. For example, avoid expressions with double negatives by rewriting !(A && B) as !A || !B for clarity and efficiency. Short-circuiting operations (&& and ||) can also enhance performance by stopping evaluation as soon as the result is determined. Coupled with creating helper methods to encapsulate complex logic and avoiding nested expressions, these strategies streamline logical evaluations for more maintainable code .

You might also like