Baixe o app para aproveitar ainda mais
Prévia do material em texto
Java – Parte III Notas de Aula Prof. André Bernardi Array Arrays uni-dimensionais � Declarando e criando � int c[]; // declare the array variable � c = new int[ 12 ]; // create the array; � int c[] = new int[ 12 ]; � double[] array1, array2; Arrays Uni-dimensionais � Inicializando int n[] = { 10, 20, 30, 40, 50 }; for ( int i = 0; i < n.length; i++ ) n[ i ] = 10 + 10*i; Arrays Uni-dimensionais � Acessando elementos com enhanced for for ( parameter : arrayName ) statement � Exemplo: for ( int i = 0; i < array.length; i++ ) total += array[ i ]; � Será substituido por: for ( int number : array ) total += number; Só pode ser utilizado para acessar, nunca para modificar Array Multi-Dimensional � int b[][] = { { 1, 2 }, { 3, 4 } }; � int b[][] = { { 1, 2 }, { 3, 4, 5 } }; � int b[][]; b = new int [ 3 ][ 4 ]; � int b[][]; b = new int[ 2 ][ ]; // cria 2 linhas b[ 0 ] = new int[ 5 ]; // cria 5 colunas b[ 1 ] = new int[ 3 ]; // cria 3 colunas Array Multi-Dimensional � Usando com duas estruturas for aninhadas int total = 0; for ( int l = 0; l < a.length; row++ ) { for ( int c = 0; c < a[ l ].length; c++ ) total += a[ l ][ c ]; } Arrays de Objetos � Quando criamos um array, do tipo de uma classe na verdade estamos criando um array de Referencias para Objetos. � Essas referencias devem ser alocadas para se utilizar: String name[] = { “B1”, “B2”, “B3”, “B4” }; JButton array[] = new JButton[name.length]; for(int i = 0; i< array.lenght; i++) array[i] = new JButton(name[i]); Exercícios 1) Crie um programa em Java que declare e inicialize dois arrays unidimensionais do mesmo tamanho, e calcule o produto escalar destes dois arrays. Por exemplo, se os dois arrays forem { 9; 2; 6; 7; 0 } e { 1; 4; 5; 9; 2 } o produto escalar será 9 x 1 + 2 x 4 + 6 x 5 + 7 x 9 + 0 x 2 = 34. Monte uma interface gráfica com JTextField s e eventos de ação para pegar os valores dos vetores e retornar o produto escalar em um JLabel. 2) Escreva uma classe que represente um numero inteiro longo com 30 dígitos. Acrescente funções que permitam que estes números possam ser somados e subtraídos. Utilize-a em um programa principal simples. Sugestão: utilize um vetor para armazenar os dígitos do numero. Layout �� FlowLayoutFlowLayout – Padrão em painéis, onde um componente é adicionado ao lado do outro. �� BorderLayoutBorderLayout – Padrão em Frames, onde os componentes ocupam regiões especificas no container. �� GridLayoutGridLayout –– Divide o container em linhas e colunas. FlowLayout BorderLayout GridLayout Usando Painéis import java.awt.*; import javax.swing.*; public class PanelFrame extends JFrame { private JPanel buttonJPanel; // panel to hold buttons private JButton buttons[]; // array of buttons public PanelFrame() { super( "Panel Demo" ); buttons = new JButton[ 5 ]; // create buttons array buttonJPanel = new JPanel(); // set up panel buttonJPanel.setLayout( new GridLayout( 1, buttons.length ) ); // create and add buttons for ( int count = 0; count < buttons.length; count++ ) { buttons[ count ] = new JButton( "Button " + ( count + 1 ) ); buttonJPanel.add( buttons[ count ] ); // add button to panel } // end for add( buttonJPanel, BorderLayout.SOUTH ); // add panel to JFrame } // end PanelFrame constructor } // end class PanelFrame Exercício 1) Utilizando Painéis e Layouts, montar a interface de uma calculadora conforme figura: Applets - Exemplos � http://java.sun.com/applets/jdk/1.3/ind ex.html � Analisar � SimpleGraph � GraphicsTest � DrawTest � http://java.sun.com/j2se/1.5.0/docs/rel notes/demos.html Applets – classe JApplet // A first applet in Java. import java.awt.Graphics; // program uses class Graphics import javax.swing.JApplet; // program uses class JApplet public class WelcomeApplet extends JApplet { // draw text on applet's background public void paint( Graphics g ) { // call superclass version of method paint super.paint( g ); // draw a String at x-coordinate 25 and y-coordinate 25 g.drawString( "Welcome to Java Programming!", 25, 25 ); } // end method paint } // end class WelcomeApplet Exemplo import java.awt.Graphics; public class GraphApplet extends javax.swing.JApplet { double f(double x) { return (Math.cos(x/5) + Math.sin(x/7) + 2) * getSize().height / 4;} public void paint(Graphics g) { for (int x = 0 ; x < getSize().width ; x++) { g.drawLine(x, (int)f(x), x + 1, (int)f(x + 1)); } } public String getAppletInfo() { return "Draws a sin graph."; } } Executar um Applet � Necessita de um código HTML, com pelo menos as seguintes tags: <html> <applet code = "WelcomeApplet.class" width = "300" height = "45"> </applet> </html> AppletViewer � Programa utilitário que é distribuído junto com a JDK. � Pode ser usado para testar os applets desenvolvidos. � Outra maneira é utilizar um Browser que execute java. Exercício 1) Apresentar a interface gráfica desenvolvida para a calculadora dentro de um Applet. Referencias � Java How to program 3, 4, 5 e 6 ed. Deitel e Deitel � Sun http://java.sun.com
Compartilhar