Computer Applications
Ravi runs the following Java code but encounters an error. Identify the statement causing the issue, correct it, and ensure the output is "Hungry".
char h = 'Y';
if (h == 'y' || 'Y')
System.out.println("Hungry");
else
System.out.println("Not Hungry");
Answer
char h = 'Y';
if (h == 'y' || h == 'Y') {
System.out.println("Hungry");
} else {
System.out.println("Not Hungry");
}
Reason — The problem lies in the condition of the if statement:
if (h == 'y' || 'Y')
The condition 'Y'
is invalid because ||
expects boolean expressions on both sides. 'Y'
alone is a char, not a boolean, causing a compilation error.
The statement can be corrected as:
if (h == 'y' || h == 'Y')
Now both sides of ||
are boolean expressions.
Related Questions
Write a program to input three numbers (positive or negative). If they are unequal then display the greatest number otherwise, display they are equal. The program also displays whether the numbers entered by the user are 'All positive', 'All negative' or 'Mixed numbers'.
Sample Input: 56, -15, 12
Sample Output:
The greatest number is 56
Entered numbers are mixed numbers.Using the switch-case statement, write a menu driven program to do the following:
(a) To generate and print Letters from A to Z and their Unicode
Letters Unicode A 65 B 66 . . . . . . Z 90 (b) Display the following pattern using iteration (looping) statement:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5Differentiate between if else if and switch-case statements
A triangle is said to be an 'Equable Triangle', if the area of the triangle is equal to its perimeter. Write a program to enter three sides of a triangle. Check and print whether the triangle is equable or not.
For example, a right angled triangle with sides 5, 12 and 13 has its area and perimeter both equal to 30.