Passing variable value obtained in one method to another method in Java

Asked

Viewed 906 times

1

The project is a school GED, where there is the main class that makes the connection to database and there is another class to generate PDF files.

The issue is that the system comes to extract the desired data from the database, but fails to insert it in the PDF file.

Look at:

Leading

import java.sql.*;
import static javax.swing.UIManager.getString;

public class Conectora {

    public static String nome;

    public static void main(String[] args){

        try {
            Statement atestamento;
            ResultSet resultado;

            String usuario = "postgres";
            String senha = "123";
            String endereco = "jdbc:postgresql://localhost:5433/ueer5";

            Class.forName("org.postgresql.Driver");

            Connection con = DriverManager.getConnection(endereco, usuario, senha);

            atestamento = con.createStatement();

            atestamento.executeQuery("SELECT * FROM alunos WHERE codigo = 1;");

            resultado = atestamento.getResultSet();

            while (resultado.next()) {

                nome = resultado.getString(2);
            }

            System.out.println(nome);//fora do while

            con.close();

            System.out.println("Conexão bem-sucedida.");

        } catch (Exception e){
            System.out.println("Conexão mal-sucedida.\n"+e);
        }

        System.out.println(nome);//fora do try-catch
    }        

}

Other class

import com.itextpdf.text.Document;
import com.itextpdf.text.Element;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Font;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.text.PageSize;
import Gertrudes.Conectora;
import static Gertrudes.Conectora.*;
import java.awt.Desktop;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Declaradora {

    public static void main(String[] args){

        String aluno = null;
        String serie = "1º";
        String nascimento = "20/01/2001";
        String mae = "Beltrana de Tal";
        String pai = "Cicrano de Tal";
        String diretor = "Dirceu E. Torquato";

        Document dec = new Document(PageSize.A4);

        try{
            PdfWriter.getInstance(dec, new FileOutputStream("dec.pdf"));

            dec.open();
            Paragraph titulo = new Paragraph("DECLARAÇÃO");
            titulo.setAlignment(1);
            titulo.setSpacingAfter(30);
            dec.add(titulo);

            Paragraph texto = new Paragraph("Declaro para os fins que se fizerem necessários que o (a) aluno (a) "+ aluno +" está matriculado (a) e cursando regularmente o  "+ serie +" ano do Ensino Fundamental neste estabelecimento de ensino no ano corrente.");
            texto.setAlignment(3);
            texto.setSpacingAfter(30);
            dec.add(texto);

            Paragraph dados = new Paragraph("Data de nascimento: "+ nascimento +"\nMãe: "+ mae +"\nPai:"+ pai );
            //dados.setAlignment(Element.ALIGN_LEFT);
            dados.setSpacingAfter(30);
            dec.add(dados);

            Paragraph assinatura = new Paragraph("____________________________\n" + diretor + "\nDiretor");
            assinatura.setAlignment(1);
            assinatura.setSpacingAfter(30);
            dec.add(assinatura);

            Paragraph local = new Paragraph("Agricolândia - PI, "+ new Date());
            local.setAlignment(2);
            //assinatura.setSpacingAfter(30);
            dec.add(local);

            dec.close();

        } catch (Exception e){
            e.printStackTrace();
        }

        try {
            Desktop.getDesktop().open(new File("dec.pdf"));
        } catch (IOException ex) {
            System.out.println("Errooouu!"+ ex);
        }
        System.out.println("nome: "+nome+"\naluno: "+aluno);
    }
}

In case, I was testing first pass only the student’s name.

  • In the method call you pass as parameter the name, in the case of a String, if you call the method and want a return within the same method, this must return a String, where you put print...name, you should return it, n? only it is as void, then returns nothing, would be something like: public String ... then in return you put return suastring, so where you call him you take this information and use it as you wish

  • Another case was to leave the name variable as static so you could access it from any class, just do String nome = minhaclasse.nomedaviaril so you’d pick her up from the other class without having to pass her

1 answer

1

Good morning, creates a student class that will be your DTO and a function in the class that connects to the database that returns that student. Class Example:

public class Aluno {

private String nomeAluno;
private int matriculaAluno;

public String getNomeAluno() {
    return nomeAluno;
}

public void setNomeAluno(String nomeAluno) {
    this.nomeAluno = nomeAluno;
}

public int getMatriculaAluno() {
    return matriculaAluno;
}

public void setMatriculaAluno(int matriculaAluno) {
    this.matriculaAluno = matriculaAluno;
}

And the method in the query class to return this:

private List<Aluno> buscaTodosOsAlunos() {
    // ...
}

I hope I helped. Good luck.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.