'I am trying to complete an else if statment in Java but it doesnt work [closed]
I want it to print "C" if 'salary' is equal to or greater than 50 but I want it to print "E" if 'salary' is greater than 70. How should I go about doing this? (P.S I am using programiz online java complier) Code:
import java.util.Scanner;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
class Main {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in);
System.out.println("Enter your Name, Student ID and Salary: \n");
// String input
String name = myObj.nextLine();
// Numerical input
int id = myObj.nextInt();
int salary = myObj.nextInt();
// Output input by user
System.out.println("\nStudent Name: " + name);
System.out.println("\nStudent ID: " + "IIBT" + id);
System.out.println("\nDate of Issue: " + java.time.LocalDate.now());
System.out.println("\nDocument ID: " + salary);
if(salary>=50) {
if(salary>=70) {
System.out.printIn("E");
}
else {
System.out.println("C");
}
}
}
}
Solution 1:[1]
You can of course rank in descending order:
if (salary >= 70) {
System.out.println("E");
} else if (salary >= 50) {
System.out.println("C");
}
Solution 2:[2]
You could put the second if inside the first.
You could also use a switch.
Personally I find it clearer to write if(salary>=70) but there is no functional difference.
if(50<=salary) {
if(70<=salary) {
System.out.println("E");
}
else {
System.out.println("C");
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 |
