Load the class dynamically and get the annotated classes

import com.this.class.Factory;
      public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {

        // Itearate over all @Factory annotated elements
        for (Element annotatedElement : roundEnv.getElementsAnnotatedWith(Factory.class)) {
            ...
        }
      }

This works when I import the annotation class in the annotation processor. But when the annotation class is loaded dynamically doesn’t works

Class<?> Factorry = class.forName("com.this.class.Factory")
 public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {

        // Itearate over all @Factory annotated elements
        for (Element annotatedElement : roundEnv.getElementsAnnotatedWith(Factory.class)) {
            ...
        }
      }

How to pass the annotated Factory.class to getElementsAnnotatedWith when the class is loaded using class.forName()

How to call the whole subclass (not one method) for the main class, is that possible? Error: cannot access

I have an assignment that I need to have two basic forms and let people type in some data and process them, finally get a report. The first basic form is for typing in the costumer number and the costumer’s name, and the second should put in job code, working hour and cost for parts. The thing I get confused is I don’t know if I should let my subclass do the second basic form. Moreover, either use subclass to subclass to do the second basic form or not, I don’t know how to call the whole subclass… Here is the code that I try to use the subclass for only some calculation, but there is error that show in a part of the constructor that cannot be accessed.

main class

package Assign_7_1;

import BasicIO.*;                // for IO classes
import static BasicIO.Formats.*; // for field formats
import static java.lang.Math.*;  // for math constants and functions


/** This class input each data by Basic Form and report them and the 
calculated data 
  * by PDF.
  *
  * @author Clover(Jiawei) Yu
  * @version 1.0 (Nov.29 2017)                                                        */

 public class jobBill {


  private BasicForm      display1;
  private BasicForm      display2;
  private ReportPrinter  report;
  private ASCIIOutputFile  invData;
  private ASCIIDataFile itemData;    
  String                 custNum;
  String                 name;


  /** This constructor create a Basic Form for input consumer info and the data
    * and report them and the calculated data.*/

  public jobBill ( ) {
    item anItem;
    int  button;
    int code;
    double hour;
    double parts;

    display1 = new BasicForm();
    display2 = new BasicForm();
    report = new ReportPrinter();

    setUpReport();
    buildForm1();
    buildForm2();

    for ( ; ; ){
        button = display1.accept();
        custNum = display1.readString();
        name = display1.readString();

        fillForm2(custNum);
        for ( ; ; ){
          button = display2.accept();
          if (button == 1) break;
            code = display2.readInt();
            hour = display2.readDouble();
            parts = display2.readDouble();
            anItem = new item();//this is where I want to call the subclass
            writeDetail(anItem);
        }; //this loop show error that cannot be visited
    };


      writeSummary(anItem);//this also show the same error
      display1.close();
      display2.close();
      invData.close();
      report.close();



    }; // constructor

    private void buildForm1(){
      display1.setTitle("Customer Info");
      display1.addTextField("custNum","Cust #",4,10,10);
      display1.addTextField("name","Name",20,10,40);
    };

    private void buildForm2(){
      display2.addTextField("custNum","Cust #",4,10,10);
      display2.setEditable("custNum",false);
      display2.addTextField("code","Job Code",3,10,40);
      display2.addTextField("hour","Hours",3,10,80);
      display2.addTextField("parts","Parts",8,10,100);
    };

    private void setUpReport(){
      report.setTitle("Wheels R Us", "Account Summary", "Customer:"+custNum+name);
      report.addField("code","Code",5);
      report.addField("hour","Hours",4);
      report.addField("labor","Labor",getCurrencyInstance(),9);
      report.addField("parts","Parts",getCurrencyInstance(),6);
      report.addField("tax","Taxes",getCurrencyInstance(),7);
      report.addField("total","Total",getCurrencyInstance(),9);
    };

    private void fillForm2(String custNum){
      display2.writeString("custNum",custNum);
    };

    private void write (int code, double hour, double parts){
      invData.writeInt(code);
      invData.writeDouble(hour);
      invData.writeDouble(parts);
      invData.newLine();
    };

    private void writeDetail(item anItem){
      report.writeInt("code",anItem.getCode());
      report.writeDouble("hour",anItem.getHour());
      report.writeDouble("labor",anItem.getLabor());
      report.writeDouble("parts",anItem.getParts());
      report.writeDouble("tax",anItem.getTaxes());
      report.writeDouble("total",anItem.getTotal());
    };

    private void writeSummary(item anItem){
      report.writeString("code","Total");
      report.writeDouble("labor",anItem.getTLabor());
      report.writeDouble("parts",anItem.getTParts());
      report.writeDouble("tax",anItem.getTTaxes());
      report.writeDouble("total",anItem.getTTotal());
    };// methods


    public static void main ( String[] args ) { jobBill j = new jobBill(); };


} // jobBill

subclass

package Assign_7_1;


import BasicIO.*;                // for IO classes
import static BasicIO.Formats.*; // for field formats
import static java.lang.Math.*;  // for math constants and functions
import java.io.*;


/** This class use to input data and calculate the total data.
  *
  * @author Clover(Jiawei) Yu
  * @version 1.0 (Nov.29 2017)                                                        */

public class item implements Serializable{

  public static final long SerialVersionUID = 987654321L;

  private BasicForm  display2;
  private ASCIIDataFile    invData;

  int code;
  double hour;
  double parts;
  double labor;
  double taxes;
  double total;
  double tLabor;
  double tParts;
  double tTaxes;
  double tTotal;
  int button;


  /** This constructor use Basic Form to input code, hour,
    * parts and calculate total, total labor, total parts,
    * total taxes, total of all for the main class.*/

  public item (){
    total = 0;
    tLabor = 0;
    tParts = 0;
    tTaxes = 0;
    tTotal = 0;


      if (100<=code && code<=199){
          labor = 0.0*hour;
          parts = 0.0*parts;
        }
      else if (199<=code && code<=900){
          labor = 60.00*hour;
          parts = 1*parts;
        }
       else if(900<=code && code<=999){
          labor = 45.00*hour;
          parts = 1*parts;
        }

    taxes = 0.13*(labor+parts);
    total = total + labor+parts+taxes;
    tLabor = tLabor + labor;
    tParts = tParts + parts;
    tTaxes = tTaxes + taxes;
    tTotal = tTotal + total;
  };



  public int getCode(){
    return code;
  };

  public double getHour(){
    return hour;
  };

  public double getParts(){
    return parts;
  };

  public double getLabor(){
    return labor;
  };

  public double getTaxes(){
    return taxes;
  };

  public double getTotal(){
    return total;
  };

  public double getTParts(){
    return tParts;
  };

  public double getTLabor(){
    return tLabor;
  };

  public double getTTaxes(){
    return tTaxes;
  };

  public double getTTotal(){
    return tTotal;
  };

  private void write(ASCIIOutputFile to){
    to.writeInt(code);
    to.writeDouble(hour);
    to.writeDouble(labor);
    to.writeDouble(parts);
    to.writeDouble(taxes);
    to.writeDouble(total);
    to.newLine();
  };

} // item

Thank you for your patience.

Java: Date from unix timestamp

I need to convert a unix timestamp to a date object.
I tried this:

java.util.Date time = new java.util.Date(timeStamp);

Timestamp value is: 1280512800

The Date should be “2010/07/30 – 22:30:00” (as I get it by PHP) but instead I get Thu Jan 15 23:11:56 IRST 1970.

How should it be done?

Traverse and print matrix by java columns

How can I traverse an array by columns? I have a hard time traversing an array and traversing by rows and that is printing if it is, but by columns for example in the matrix.

Going through and printing by rows is like this:

for (int i = 1; i <= size; i++) {
        for (int j = 1; j <= size; j++) {
            System.out.print(matrix[i][j] + " ");
        }
        System.out.println();
    }



1  2  3  4  5
6  7  8  9  10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25

First print the first column 1 6 11 16 21, then the second and so on.

Can’t import java.lang.reflect in maven project?

I’m trying to import java.lang.reflect in a java file of a maven project, but I get “error cannot find symbol” on the import line. It can’t find java.lang either. This is a built in Java lib, right? I didn’t think I needed to add any dependencies for a default java lib. Is there a certain dependency I need to define to gain access to this lib?

is Array is Abstract data structure [on hold]

a-Define the term Abstract Data Type (ADT), show why an array can be considered an ADT and the difference between the concrete representation as an array and the abstract as a list.
b-Give two situations why an array can never be used as a data structure, and how a linked list structure is the optimal option.

MySQL to JSP using Servlet

I am trying to retrieve data from one column of my table in MySQL and display the whole row in a .jsp file. Right now, when I run the code it prints the table with no values. As Shown here.

import java.sql.*;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mysql.jdbc.PreparedStatement;

@WebServlet("/review")
public class findservlet1 extends HttpServlet {
  /**
     * 
     */
    private static final long serialVersionUID = 8402378218178447403L;

public void doGet(HttpServletRequest req, HttpServletResponse res)
                               throws ServletException, IOException {

   // res.setContentType("text/html");
    PrintWriter out = res.getWriter();
    Connection conn = null;
       //using movie_resolved view
    try{
      // Get a Connection to the database
        String DB_CONNECTION_URL = "jdbc:mysql://localhost:3306/mydatabase";
        String DB_USERNAME = "root";
        String DB_PASSWORD = "root";
        Class.forName("com.mysql.jdbc.Driver");
        Connection con = DriverManager.getConnection(DB_CONNECTION_URL, DB_USERNAME, DB_PASSWORD);
     // Create a Statement object
         PreparedStatement st = (PreparedStatement) con.prepareStatement("SELECT * FROM coursereview");

         ResultSet rs = st.executeQuery();

     if (rs.next())
      {

         com.java.bean.coursereview Course = new com.java.bean.coursereview ();
         Course.setCourse_id(rs.getString("courseid"));
         Course.setCourserate(rs.getString("courserate"));
         Course.setProfessor(rs.getString("professor"));
         Course.setProrate(rs.getString("prorate"));
         Course.setReview(rs.getString("review"));
        req.setAttribute("Course", Course);
        RequestDispatcher view = req.getRequestDispatcher("review.jsp");
          view.forward(req, res);
      }


    }
    catch(ClassNotFoundException e) {
     out.println("Couldn't load database driver: " + e.getMessage());
    }
    catch(SQLException e) {
      out.println("SQLException caught: " + e.getMessage());
    }
    finally {
      // Always close the database connection.
      try {
        if (conn != null) conn.close();
      }
      catch (SQLException ignored) { }
   }
  }
}

Here is my reivew page:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<link rel="stylesheet" href="styles/style1.css">
<meta http-equiv="Content-Type" content="text/css; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

<div class="banner">
    <img class="banner-image" src="images/uncclogo400.jpg"></div>
  <h2>Review a Course</h2>
  <table>
        <TR>
            <TD>Course ID: </TD>
            <TD>${course.courseid}</TD>
        </TR>

        <TR>
            <TD>Course Rate: </TD>
            <TD>${course.courserate}</TD>
        </TR>
         <TR>
            <TD>Professor: </TD>
            <TD>${course.professor}</TD>
        </TR>
        <TR>
            <TD>Professor Rate: </TD>
            <TD>${course.prorate}</TD>
        </TR>
        <TR>
            <TD>Review: </TD>
            <TD>${course.review}</TD>
        </TR>

        </table>
</body>
</html>

I am trying to pull the values from the MySQL DB to print to the review.jsp page. Any ideas on what I am doing wrong?

How can I use BufferedReader to read two files?

I’m starting to learn how to work with files and I”m doing a program that read a file with grades and after doing this, i have to create a file with the grades and the average, i’m trying to read this in the end, i create another BufferedReader and use while (bufferedReader2.ready()), but it didn’t work anything that was on the while. How I can fix this?

Calculating MPG for each leg of a trip, JAVA

import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.geometry.HPos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.RadioButton;
import javafx.scene.control.TextField;
import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.GridPane;
import javafx.scene.paint.Color;
import javafx.stage.Stage;

public class MPGCalc extends Application {
    private TextField tfMiles = new TextField();
    private TextField tfGallons = new TextField();
    private TextField tfMiles1 = new TextField();
    private TextField tfGallons1 = new TextField();
    private TextField tfMiles2 = new TextField();
    private TextField tfGallons2 = new TextField();
    private TextField tfMiles3 = new TextField();
    private TextField tfGallons3 = new TextField();
    private TextField tfMiles4 = new TextField();
    private TextField tfGallons4 = new TextField();

    private Button calcMPG = new Button("Calculate");
    private TextField displayMPG = new TextField();
    private RadioButton rbStandard = new RadioButton("Standard");
    private RadioButton rbMetric = new RadioButton("Metric");
    private Label lblDistance = new Label("Miles:");
    private Label lblAmount = new Label("Gallons:");
    private Label lblDistance1 = new Label("Miles:");
    private Label lblAmount1 = new Label("Gallons:");
    private Label lblDistance2 = new Label("Miles:");
    private Label lblAmount2 = new Label("Gallons:");
    private Label lblDistance3 = new Label("Miles:");
    private Label lblAmount3 = new Label("Gallons:");
    private Label lblDistance4 = new Label("Miles:");
    private Label lblAmount4 = new Label("Gallons:");

    private Label lblMPG = new Label("MPG:");

    @Override // Override the start method in the Application class
    public void start(Stage primaryStage) {
        // Create UI
        GridPane gridPane = new GridPane();
        gridPane.setHgap(5);
        gridPane.setVgap(5);
        gridPane.add(rbStandard, 0 ,0);
        gridPane.add(rbMetric, 1, 0);

        gridPane.add(lblDistance, 0, 1);
        gridPane.add(tfMiles, 1, 1);
        gridPane.add(lblAmount, 0, 2);
        gridPane.add(tfGallons, 1, 2);

        gridPane.add(lblDistance1, 0, 3);
        gridPane.add(tfMiles1, 1, 3);
        gridPane.add(lblAmount1, 0, 4);
        gridPane.add(tfGallons1, 1, 4);

        gridPane.add(lblDistance2, 0, 5);
        gridPane.add(tfMiles2, 1, 5);
        gridPane.add(lblAmount2, 0, 6);
        gridPane.add(tfGallons2, 1, 6);

        gridPane.add(lblDistance3, 0, 7);
        gridPane.add(tfMiles3, 1, 7);
        gridPane.add(lblAmount3, 0, 8);
        gridPane.add(tfGallons3, 1, 8);

        gridPane.add(lblDistance4, 0, 9);
        gridPane.add(tfMiles4, 1, 9);
        gridPane.add(lblAmount4, 0, 10);
        gridPane.add(tfGallons4, 1, 10);

        gridPane.add(calcMPG, 0, 11);
        gridPane.add(displayMPG, 1, 12);
        gridPane.add(lblMPG, 0, 12);


        // Set properties for UI
        gridPane.setAlignment(Pos.CENTER);
        tfMiles.setAlignment(Pos.BOTTOM_RIGHT);
        tfGallons.setAlignment(Pos.BOTTOM_RIGHT);
        calcMPG.setAlignment(Pos.BOTTOM_RIGHT);
        displayMPG.setAlignment(Pos.BOTTOM_RIGHT);
        displayMPG.setEditable(false);      
        ToggleGroup group = new ToggleGroup();
        rbStandard.setToggleGroup(group);
        rbMetric.setToggleGroup(group);


        // Process events
        calcMPG.setOnAction(e -> calculateMPG());

                rbStandard.setOnAction(e -> rbStandard());

                rbMetric.setOnAction(e -> rbMetric());

        // Create a scene and place it in the stage
        Scene scene = new Scene(gridPane, 400, 250);
        primaryStage.setTitle("MPG Calculator"); // Set title
        primaryStage.setScene(scene); // Place the scene in the stage
        primaryStage.show(); // Display the stage
                rbStandard.setSelected(true);
    }

    private void calculateMPG() {
            double gallons = Double.parseDouble(tfGallons.getText());
            double miles = Double.parseDouble(tfMiles.getText());

            double mpg = miles / gallons;

            displayMPG.setText(String.format("%.2f", mpg));

    }

        private void rbStandard(){

            lblDistance.setText("Miles:");
            lblAmount.setText("Gallons:");        
            lblMPG.setText("MPG:");

            double liters = Double.parseDouble(tfGallons.getText());
            double kilometers =  Double.parseDouble(tfMiles.getText());
            double kml = Double.parseDouble(tfMiles.getText());

            double gallons  = liters / 3.785411784;
            double miles = kilometers * 1.6;
            double mpg = miles / liters;

            tfGallons.setText(String.format("%.2f", gallons));
            tfMiles.setText(String.format("%.2f", miles));
            displayMPG.setText(String.format("%.2f", mpg));



        }


        private void rbMetric(){

            lblDistance.setText("Kilometers:");
            lblAmount.setText("Liters:");        
            lblMPG.setText("KM/L:");

            double gallons = Double.parseDouble(tfGallons.getText());
            double miles = Double.parseDouble(tfMiles.getText());
            double mpg = Double.parseDouble(tfMiles.getText());

            double liters = gallons * 3.785411784;
            double kilometers = miles/1.6;
            double kml = miles / liters;

            tfGallons.setText(String.format("@%.2f", gallons));
            tfMiles.setText(String.format("@%.2f", miles));
            displayMPG.setText(String.format("@%.2f", mpg));

        }

    /**
     * The main method is only needed for the IDE with limited
     * JavaFX support. Not needed for running from the command line.
     */
    public static void main(String[] args) {
        launch(args);
    }
}

This started out as just a MPG calculator but now I am trying to make it calculate the MPG for up to 5 stops in a trip, and then at the end of the 5 stops, calculate the final MPG for the trip. Right now it will calculate the MPG for the first stop, but afterwards it leaves out the inputs for the text fields 1-4. I tried setting the getText in the calculateMPG to the correct text fields but it still didn’t change the output. I also thought about just making several methods for each leg but I wasn’t sure if there was a more efficient way to do it. Thanks for the help.