quinta-feira, 25 de março de 2010

Comments, operators, loops and arrays

Hello everybody!


Today end our visit in the general features of Java. We will see now how are the comments, operators, loops and arrays of language.
Comments

Java has three kinds of comments. A double slash (/ /) will cause the compiler to ignore everything that is used until the end of the line. Similarly, all that is between the characters / * and * / is also ignored by the compiler. These two forms are similar to comments in C / C + +.


If the first part of a comment starts with / **, is given a special feature of docmentação, and will use the javadoc utility, present in the JDK from Sun With the javadoc, it is possible to document an entire package of classes, it is generated an HTML file automatically from Java code. The comments should be part of the HTML text are marked, appearing between / ** and * /. You can specify additional information for each method using keywords such as stop, returns and exception (documenting parameters, return values and exceptions issued, respectively), for example. These keywords must be preceded by the @ symbol.




Operators


Working with operators in Java is very simple. Declare the following code, two integers. After the declaration, they are added together and result in a third variable.



int x, y;


x = 4;


y = 5;


int z = x + y;


The final value is 9.
Consider a table with the classification of operators:
Classification Operators
Arithmetic + - * /%
Relational Operators <>> = <= ==! = & &


!


Bitwise &
^ <<>>>>> ~ & = = ^ =


Assignment = + = -= / =% =


Assignments bitwise & = = <<=>> =>> = ^ =


Ternary operator?:


+ Increase


Decrement --



The expressions that have multiple operators are resolved according to the position where they are in a hierarchy of precedence. The traders at higher positions in the table of precedence are evaluated first. If several operators located in the same line have equal precedence, they are resolved in order from left to right. The following list shows the table of precedence:




. [] ()


+ + -! ~
* /%
+ -- <<>>>>>>
<> <=> =
==! =
& ^
& & ?: =


and other assignments



- Role bitwise


Loops



Java has three operations loop. The loop for the construction is structured as follows:



for (init; test, post-test)




The first part of the expression is any initialization that occurs at the beginning of the loop. The test is a simple or complex expression. The last part is an expression, as the increment or decrement a variable. The for loop is followed by a final statement or a block of code. For example:


for (k = 0), k <10; k + +) (


/ / .. do something


)






The above code goes in loop ten times.


A while loop is a portion of the test loop:


while (test)


The construction of the ... while performing the test and the end of the loop:
do (


/ / ... do something


) While (test)

The building is used to break out of a loop, while the continue statement jumps to the next iteration of the loop. Can also be used loops labeled, in order to control the location where the control should go in loops complex. If a label after a break statement, then the code exits the loop closest to the label that has coincidental. The following example effectively terminating both loops when the variable j is greater than 100:



int i, j;


quit: for (i = j = 0; i <100; + + i) (


for (int k = 0, k <10; k + +) (


/ / ... do something


if (j> 100)


UPS quit;


)


)

Arrays

Arrays in Java are not simply memory pointers as in C. They are much safer. You may not assign any content to an array, because Java makes sure that it is valid. This avoids many situations where there is a breach of memory access that are difficult to control. If you try to access an invalid array index, Java will launch an obvious exception, and no action is taken.
Because the arrays are Java objects, their semantics is somewhat different from their counterparts in C / C + +. First, you can not declare an array of default size, it must be declared as an uninitialized variable:
int numbers [], / / arrays for integers

Ex_String String [], / / for arrays of string objects

We can declare variables of arrays placing the brackets after the type. This method has a greater readability:

String [] ex_String;

Next, we will use the new constructor to build an object instance and create the array:

int numbers [] = new int [5] / / for integer arrays of length 5
Ex_String String [] = new String [20] / / for arrays of objects string of length 20

The previous examples create an array of integers of length 5 and an array of strings of length 20. Arrays, however, still have nothing. Each item is initialized with a default value. The integers are set by default to 0, and the string are set to null.
Add elements to the array is simple. The system starts at 0 and has integer indices. To assign the first element would be used:
ex_String [0] = "First element"




numbers [0] = 10;

Java does not multidimensional arrays. However, we can simulate them by using arrays of arrays. We can determine the array sizes with pre-determined as follows:




int k [] [] = new int [5] [4];

k [1] [3] = 999 / / assign a value to the array

This example creates an array of 4 x 5 arrays, assigned to the variable k. The second line shows that the assignment of an element to the array is simple and similar to the process of C / C + +.


segunda-feira, 22 de março de 2010

Generating reports with iReport and Java


Hello,

This topic is intended to inform, step by step, how to create a report with iReport and run it through a java application.
For better understanding, it will work with the project in a layer structure, all files will be in the root folder of the project.

• Tools used:
• iReport-1.2.5
• Java (version jre1.5.0_06)
• Eclipse (Lomboz)
• MySQL 5.0.18

Let's assume that you already created a schema in mysql named myproject

Run this script to create the table and insert some records:/*


MySQL Backup


Source Host: localhost

Source Server Version: 5.0.18-nt

Source Database: meuprojeto


Date: 2006/11/29 21:27:23

*/




SET FOREIGN_KEY_CHECKS=0;

use meuprojeto;


#----------------------------

# Table structure for tb_produtos


#----------------------------

CREATE TABLE `tb_produtos` (


`cod` int(11) NOT NULL auto_increment,

`descricao` varchar(50) character set latin1 collate latin1_general_ci default NULL,


`preco` double default NULL,


PRIMARY KEY (`cod`)


) ENGINE=MyISAM DEFAULT CHARSET=latin1;


#----------------------------


# Records for table tb_produtos


#----------------------------










insert into tb_produtos values


(1, 'camisa', '20'),


(2, 'calça', '30'),


(3, 'perfume', '70'),


(4, 'cinto', '20'),


(5, 'sapato', '100'),


(6, 'cueca', '10'),


(7, 'teste', '10');


We have created the schema, table and some records, we will open the iReport to create the report:

Open iReport and if you do not have an active connection, follow the steps below:




• In the menu, click Data and then Connectio / Datasources, you will have a screen like this:
 

• Click new and set as pictured below:


• If the User requires root password, enter it in PassWord

• Click Test to verify the connection and then click Save.

• You return pala the previous window, select the connection and click Set as Default.

• Close the window


Let's create the report as quickly and practice


• Click File Report Wizard

• In the report to query for the report, as stated:
 

Click Next on the next window, place all items to the right window, as shown and click Next


• We will sort by group, click Next again


• In the next window, select Tabular Layout and classicT.xml, as shown:
 

•Clique em Next e em Encerrar


Voce terá algo assim:














Locate these buttons



 
The first compiles the report, the second shows the structure (no data) and the third displays the report with the data.


If you have not saved the report, anyone that you click, it will ask to save, do this and name the report.

Make some tests with the buttons, if the report is not displayed, check the previous steps as this point, you should see the report ready.

If it did all right, let's change the title, double click on it and change to the Dangerous Goods, see:


and stay that way.


Save the report again and close the iReport.
 
Remember that the report was saved with the extension. Jrxml?



Well, this file is usually used for editing the report, but what we use is what led to the iReport extençsão. Jasper.



Verify that it is already in the folder where you installed the iReport later, when we are creating a Java application, they must be copied to the root of the project. At the opportune time to remind you ...



At this point we already have the report ready, let's create the application.



At this point, are not necessary the views of images, just inform you that files should be created (from substance), which will be saved and other files to be copied, ok?



Open Eclipse, create a new java project named ProjRelatorio.

With the project selected, click the right mouse button and click New, and Folder, then name it lib Above all, we will bring the package files for the iReport project.



Go to the lib directory of iReport and copy the following files to the lib folder of your project.


Check the image:
 
 


Note that the last file mysql-connector-java-3.1.12-bin.jar may have a different version than you find in the lib folder, no problem.


Files copied? We will inform the project that they exist.
• With the project selected click Project Properties
• In the window that opens click Java Build Path
• Libraries Select window and click Add JARs

• Expand without project, click the lib folder, select all the files, click OK and OK again.
 
 
 
 
 
 
 
 


public class ExcRepositorio extends Exception {
public ExcRepositorio(String mensagem) {
 super(mensagem);
 }
}


 Save as: gConexao.java
import java.sql.Connection;



import java.sql.DriverManager;


import java.sql.SQLException;






public class gConexao {


private static Connection con;


public static Connection getConexao() throws ExcRepositorio {


String driver = "com.mysql.jdbc.Driver";


String url = "jdbc:mysql://localhost:3306/meuprojeto";


String login = "root";


String senha = "";


try {


Class.forName(driver);


con = DriverManager.getConnection(url, login, senha);


} catch (ClassNotFoundException e) {


throw new ExcRepositorio("Driver não encontrado: " + e.getMessage());


} catch (SQLException e) {


throw new ExcRepositorio("Erro abrindo conexão: " + e.getMessage());


}


return con;


}


}

 
 
Save as: principal.java  
import javax.swing.JOptionPane;



import net.sf.jasperreports.engine.JRException;


import net.sf.jasperreports.engine.JasperPrint;


import net.sf.jasperreports.view.JasperViewer;






public class principal {


public static void main(String[] args) throws JRException {


repositorioProduto rep = new repositorioProduto();


JasperPrint relat;






//Insere mais um produto e exibe o relatório


String desc = JOptionPane.showInputDialog("Descrição do produto: ");


double valor = Double.parseDouble(JOptionPane.showInputDialog("Valor: "));


produto prod = new produto(desc,valor);






try {


rep.inserir(prod);


relat = rep.gerar();


JasperViewer.viewReport(relat, false);


} catch (ExcRepositorio e) {


JOptionPane.showMessageDialog(null, "Erro: " + e.getMessage());


}


}


}



Save as: produto.java
public class produto {



private int cod;


private String descricao;


private double preco;






public produto(String desc, double preco){


this.setDescricao(desc);


this.setPreco(preco);


}


public int getcod() {return cod;}


public String getDescricao() {return descricao;}


public double getPreco() {return preco;}






public void setcod(int cod) {


this.cod = cod;


}


public void setDescricao(String desc){


this.descricao = desc;


}


public void setPreco(double pc){


this.preco = pc;


}


}



Save as: repositorioProduto.java
import java.sql.Connection;



import java.sql.SQLException;


import java.sql.Statement;


import java.util.HashMap;



import javax.swing.JOptionPane;



import net.sf.jasperreports.engine.JRException;


import net.sf.jasperreports.engine.JasperFillManager;


import net.sf.jasperreports.engine.JasperPrint;






public class repositorioProduto{






public repositorioProduto() {}






public void inserir(produto prod) throws ExcRepositorio{


String desc = prod.getDescricao();


double preco = prod.getPreco();


String SQL = "insert into tb_Produtos (descricao, preco) values " +


"('" + desc + "', " + preco + ")";






Connection conn = null;


Statement stat = null;


try {


conn = gConexao.getConexao();


stat = conn.createStatement();


stat.executeUpdate(SQL);


} catch (SQLException e) {


throw new ExcRepositorio("Erro na conexão ao inserir: " + e.getMessage());


} finally {


if (stat != null) {


try {


stat.close();


} catch (SQLException e) {


throw new ExcRepositorio("Erro ao fechar conexão: " + e.getMessage());


}


}


}


}


public JasperPrint gerar() throws ExcRepositorio{


JasperPrint rel = null;


try {


Connection con = gConexao.getConexao();


HashMap map = new HashMap();


String arquivoJasper = "relatorio.jasper";


rel = JasperFillManager.fillReport(arquivoJasper, map, con);


} catch (JRException e) {


JOptionPane.showMessageDialog(null,e.getMessage());


}


return rel;


}


}

We will now copy the files relatorio.jrxml and relatorio.jasper iReport folder to the root folder of your project (only need the. Jasper, but leave a copy of jxml as security.).



Phew! Now just run, you are prompted to insert data from a product, do this and I see it included in the report that will be displayed.

How to compile a program?



After installing the JDK, just use the program "javac" to compile your files. Java. The mean javac "Java Compiler". For example, say you have created a file called PrimeroTeste.java.






To compile it, type:










javac PrimeiroTeste.java






The javac should be in your path. He is in the installation directory of your java in the / bin.










How do I run a program in Java?










Excecute it with the command "java" followed by the name of the file without extension. For example, if you compiled a program called PrimeiroTeste.java, you see that was created a file called PrimeroTeste.class, which is the binary code of your program. To run it, simply type










java PrimeiroTeste






Note that only reported the name of Progarm, without any extension. This will cause the JVM, Java Virtual Machine is started, and "charge" your class by running it.






When trying to run any program the following error occurs:






Exception in thread "main": Java.lang.NotClassDefFoundError






You're typing the name of your class correctly? Remember that java is case sensitive, ie it is case sensitive!






This error can also occur when the CLASSPATH variable is not properly configured. The most common mistake is forgetting to add the current directory (specified by a point) to the CLASSPATH. Sometimes this variable is set as follows:










CLASSPATH = / home / user / java / algum_pacote.jar






Note that in this case only that the CLASSPATH pointing to the file "algum_pacote.jar", not containing the "point". The correct in this case is










CLASSPATH =.: / home / user / java / algum_pacote.jar






Note: The same goes for Windows, with the difference that the directories are separated by a semicolon instead of colon.






Also make sure you are in the right place! You should be in the directory where the class is, or if it is a class within a package (there is a package statement), you should be in the "root" of the package, and call the java with the full name class.






When trying to run a program, it does the following error:






Exception in thread "main" java.lang.NoClassDefFoundError: myprogram / class






Very close to the previous problem, this is actually the lack of attention to trying to run the program. As explained above, we run the programs made in Java without using the file extension. In the example above, the User tried to run the program as follows:










java MeuPrograma.class






Thus, the Java program tries to find the "class" within a directory (package) called "myprogram", which of course does not exist. To resolve, just run like this:










java myprogram






When running the program, gives the following error:






java.lang.NoSuchMethodError: main






One of the classic mistakes of the gang that starting in Java. This error occurs when a program that does not contain a valid declaration of main () function is executed. Consider the following examples:










1 JavaMainBug1.java2 public class JavaMainBug13 (4 public void hello () 5 (6 System.out.println ( "Hello");) 7) 8






Compile (javac JavaMainBug1.java) and try running (java JavaMainBug1).






Note that the error (java.lang.NoSuchMethodError: main) occurs. This is because it has not been declared the function main ().






To solve the problem, simply add the following:










1 public static void main (String args []) 2 (3)










The function main () must necessarily be "void", and contain an array of parameter,


type String. See this another example:










1 JavaMainBug2.java2 public class JavaMainBug23 (4 public static void main () 5 (6 System.out.println ( "Hello");) 7) 8






Compile it and try to run. The problem here is the lack of the parameter to the function. A final problem that is likely to occur is to define the main () function like this:










1 public static void main (String args)






Note that the variable "args" in this case is not an array, when in fact it should be.






Other examples of signature of main method that are not as usual, but they work:










1 public static void main (String args []) 2 static void main (String [] args) 3 final public synchronized void main (String arguments []) 4 ...






Do not worry if you do not understand these lines of reporting the main, practicing java you understand them.






How do I see which version of Java I'm running?






Use the command:










java-version






I created a file called PrimeiroTeste.java, but the compiler refuses to compile it, and because I have to use the extension. "Java" in the source code files?






The javac compiler assumes that any file with Java source code should have the extension. Java. Anything short of that do not reach the initial process of compilation.

Programming and Technology

Blog dedicated to programming in PHP, JAVA and everthing that relates to technology.