Anshul Rawat
Anshul Rawat

Reputation: 1

How to return a String If Boolean is True

In the Student class, a constructor is written with some value. I want to print Yes or No in the VIP Column. i.e Yes when the boolean value is true and vice-versa.

public class Student {

private String firstName;
private String lastName;
private boolean goldCustomer;

   public Student(String firstName, String lastName, boolean goldCustomer) {
      super();
      this.firstName = firstName;
      this.lastName = lastName;
      this.goldCustomer = goldCustomer;
   }

  public String getFirstName() {
    return firstName;
  }

  public void setFirstName(String firstName) {
    this.firstName = firstName;
  }

  public String getLastName() {
    return lastName;
  }

  public void setLastName(String lastName) {
    this.lastName = lastName;
  }

  public boolean isGoldCustomer() {
    return goldCustomer;
  }

  public void setGoldCustomer(boolean goldCustomer) {       
    this.goldCustomer = goldCustomer;       
  }

}

My JSP page

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page import="java.util.* , com.jsptag.demo.Student" %>
<%
  List<Student> students = new ArrayList< >();
  students.add( new Student("Rahul" , "Rawat" , false));
  students.add( new Student("Rohit" , "Negi" , true));
  students.add( new Student("Mahesh" , "Gupta" , false));   
  pageContext.setAttribute("myStudents", students);
%>

<html>
<body>
<table border="1">
  <tr>
     <th>First Name</th>
     <th>Last Name</th>
     <th>VIP ?</th>
  </tr>
  <c:forEach var="data" items="${myStudents}">
    <tr> 
      <td>${data.firstName}</td> 
      <td>${data.lastName}</td>  
      <td>${data.goldCustomer}</td> 
    </tr>   
  </c:forEach>  
</table>
</body>
</html>

Upvotes: 1

Views: 693

Answers (1)

Jan B.
Jan B.

Reputation: 6468

It should work with the ternary operator:

<td> ${data.goldCustomer ? 'Yes' : 'No'} </td>

Upvotes: 5

Related Questions