Sie sind auf Seite 1von 44

MAJS - JAVA

ESTRUTURA BSICA DE UM PROGRAMA


JAVA

Forma Geral
public class Introducao {
public static void main (String args[]) {
System.out.println(Oi!");
}
}

main (...) incio da execuo


toda instruo deve ser encerrada por ;
salvar o programa:
com o mesmo nome da classe ( idntico )
extenso .java
conveno:
cada palavra do nome em maisculo
Introducao, ExemploDePrograma

MAJS - JAVA

Objeto de Sada

System.out
Exibe as informaes na janela de comando

public class OutroExemplo {


public static void main (String args[]) {
/* Note um comentrio
dividido em mais de uma linha */
System.out.print(Usando ");
System.out.println(print e println");
}
} // fim da classe - apenas um comentrio de linha

Obs: System.out.println(1 \n 2 \n 3");


Sada:

1
2
3

MAJS - JAVA

Objeto de Sada

public class OutroExemplo {


public static void main (String args[]){
System.out.println(Mudando \n de");
System.out.println(linha");
}
}
Qual a sada?

CARACTERES DE CONTROLE
\n
nova linha
\renter
\t
tabulao (tab)
\b
retrocesso
\
aspas
\\
barra

MAJS - JAVA

Usando Caixas de Dilogos

import javax.swing.JOptionPane
public class Janela {
public static void main (String args[]){
JOpptionPane.showMessageDialog(null,
Um Exemplo em uma Janela");
System.exit(0);
}
}

importamos
(interface
JOptionPane

do
pacote
grfica)

javax.swing
a
classe

MAJS - JAVA

Usando Caixas de Dilogos

Observaes:
System uma classe que faz parte do pacote
java.lang
No necessrio importar java.lang.*
importado em todos os programas java
O mtodo exit utilizado para indicar que o
aplicativo encerrou:
0, com sucesso
Outro valor, sem sucesso

MAJS - JAVA

Leitura

import javax.swing.JOptionPane;
public class Leitura {
public static void main (String args[]){
String entrada;
int numero1, numero2, soma;
entrada = JOpptionPane.showInputDialog(digite o
nmero");
numero1 = Integer.parseInt ( entrada );
entrada = JOpptionPane.showInputDialog(digite o
nmero");
numero2 = Integer.parseInt ( entrada );
soma = numero1 + numero2;
JOpptionPane.showMessageDialog(null,a soma = +
soma);
System.exit(0);
}
}

MAJS - JAVA

Leitura

MAJS - JAVA

Variveis

um objeto que pode assumir diferentes valores

espao de memria de um certo tipo de dado


associado a um nome para referenciar seu
contedo

exemplo:
int idade;
idade = 30;
String nome = Jose;

MAJS - JAVA

DECLARANDO VARIVEIS

Instruo para reservar uma quantidade de


memria para um certo tipo de dado, indicando o
nome pelo qual a rea ser referenciada

Na sua forma mais simples:


tipo nome-da-varivel;
ou
tipo nome1, nome2, ... nomen;

ex:

int a;
int b;

ou

ex 2:

char letra;
int nmero, idade;

ex3:

main ( ... )
{
int
x;
float y;
x = 3;
y = 3 * 4.5;
...
}

int a, b;

MAJS - JAVA

NOMES DE VARIVEIS

comece com letras ou sublinhado:


seguidos de letras, nmeros ou sublinhados

obs:

sensvel ao caso:
peso <>
Peso

<>

pEso

no podemos definir um identificador com o mesmo


nome que uma palavra chave

Palavras Chave:
static

int

if

while

etc

10

MAJS - JAVA

Operadores

Operador
() []
! ++ -- + - (tipo)
* / %
+ - (binrio)
>> <<
< <= >= >
== !=
||
&&
?:
= += -= *= /= %=
>>= <<= &= |= ^=

11

MAJS - JAVA

Operadores

public class Increment {


public static void main( String args[] )
{
int c;
c = 5;
System.out.println( c ); // print 5
System.out.println( c++ ); // print 5
System.out.println( c ); // print 6
System.out.println();
c = 5;
System.out.println( c ); // print 5
System.out.println( ++c ); // print 6
System.out.println( c ); // print 6
}
}

12

MAJS - JAVA

Repetio
import javax.swing.JOptionPane;
public class Average1 {
public static void main( String args[] )
{
int total,
gradeCounter, // number of grades entered
gradeValue, // grade value
average;
// average of all grades
String grade;
// grade typed by user
// Initialization Phase
total = 0;
gradeCounter = 1;
// Processing Phase
while ( gradeCounter <= 10 ) {
grade = JOptionPane.showInputDialog("Enter integer grade: " );
gradeValue = Integer.parseInt( grade );
total = total + gradeValue;
gradeCounter = gradeCounter + 1;
}
average = total / 10; // perform integer division
JOptionPane.showMessageDialog( null, "Class average is " + average,
Class Average", JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 );

// terminate the program

} // end method main


} // end class Average1

13

MAJS - JAVA

Observao

JOptionPane.ERROR_MESSAGE
JOptionPane.WARNING_MESSAGE
JOptionPane.QUESTION_MESSAGE
JOptionPane.INFORMATION_MESSAGE
JOptionPane.PLAIN_MESSAGE

JOptionPane.showMessageDialog( null, mensagem,


Barra de Ttulo, cone );

14

MAJS - JAVA

Repetio

WHILE

while (condicao)
comando;

while (condicao) {
comando1;
comando2;
...
comandoN;
}

DO / WHILE

do
comando;
while (condicao);

do {
comando1;
...
comandoN;
} while (condicao);

15

MAJS - JAVA

Repetio

public class Test {


public static void main( String args[] )
{
int count = 0;
do
System.out.println("cont = " + cont);
while (cont <= 10);
}
}
public class Test {
public static void main( String args[] )
{
int count = 0;
do {
System.out.println("cont = " + cont);
} while (cont <= 10);
}
}

16

MAJS - JAVA

Repetio

FOR
For (expresso1; expresso2; expresso)

import javax.swing.JOptionPane;
public class Sum {
public static void main( String args[] )
{
int sum = 0;
// sum even integers from 2 through 100
for ( int number = 2; number <= 100; number += 2 )
sum += number;
// display results
JOptionPane.showMessageDialog( null, "The sum is " +
sum, "Sum Even Integers from 2 to 100",
JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 );
}
}

17

MAJS - JAVA

Lembre-se
import javax.swing.*;
public class LogicalOperators {
public static void main( String args[] )
{
// create JTextArea to display results - Line, column
JTextArea outputArea = new JTextArea( 17, 20 );
// attach JTextArea to a JScrollPane
JScrollPane scroller = new JScrollPane( outputArea );
String output;
// create truth table for && operator
output = "Logical AND (&&)" +
"\nfalse && false: " + ( false && false ) +
"\nfalse && true: " + ( false && true ) +
"\ntrue && false: " + ( true && false ) +
"\ntrue && true: " + ( true && true );
// create truth table for || operator
output += "\n\nLogical OR (||)" +
"\nfalse || false: " + ( false || false ) +
"\nfalse || true: " + ( false || true ) +
"\ntrue || false: " + ( true || false ) +
"\ntrue || true: " + ( true || true );
// create truth table for & operator
output += "\n\nBoolean logical AND (&)" +
"\nfalse & false: " + ( false & false ) +
"\nfalse & true: " + ( false & true ) +
"\ntrue & false: " + ( true & false ) +
"\ntrue & true: " + ( true & true );

18

MAJS - JAVA

Lembre-se
// create truth table for | operator
output += "\n\nBoolean logical inclusive OR (|)" +
"\nfalse | false: " + ( false | false ) +
"\nfalse | true: " + ( false | true ) +
"\ntrue | false: " + ( true | false ) +
"\ntrue | true: " + ( true | true );
// create truth table for ^ operator
output += "\n\nBoolean logical exclusive OR (^)" +
"\nfalse ^ false: " + ( false ^ false ) +
"\nfalse ^ true: " + ( false ^ true ) +
"\ntrue ^ false: " + ( true ^ false ) +
"\ntrue ^ true: " + ( true ^ true );
// create truth table for ! operator
output += "\n\nLogical NOT (!)" +
"\n!false: " + ( !false ) +
"\n!true: " + ( !true );
outputArea.setText( output ); // place results in JTextArea
JOptionPane.showMessageDialog( null, scroller,
"Truth Tables", JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 ); // terminate application
}
}
19

MAJS - JAVA

Condicional

If (condio)
comando

If (condio)
comando
else
comando

If (condio) {
comandos;
}
else {
comandos;
}

20

MAJS - JAVA

Condicional

Switch (opo) {
case 1:
comando;
break;
case 2:
comando;
break;
...
default:
comando;
}

21

MAJS - JAVA

Funes - Mtodos

Funes : abstraes de expresses

Procedimentos: abstraes de comandos

Dividir uma tarefa complexa em tarefas menores,


permitindo esconder detalhes de implementao

Evita-se a repetio de um mesmo cdigo

Forma Geral:
Tipo Nome (lista de parmetros) {
corpo
}

22

MAJS - JAVA

Funes - Mtodos
Exemplo:
static int fatorial (int n)
{
int i, resultado = 1;
for ( i = 1; i <= n; i ++)
resultado *= i;
return resultado;
}
... main (String Args[ ] ) {
System.out.println (Fatorial de 4 = + fatorial(4) );
}

23

MAJS - JAVA

VARIVEIS LOCAIS

Variveis declaradas dentro de uma funo so


denominadas locais e somente podem ser usadas
dentro do prprio bloco
So criadas apenas na entrada do bloco e
destrudas na sada (automticas)

Ex:
static void desenha ( )
{
int i, j;
. . .
. . .
}
... main (String args[ ])
{
int a;
desenha();
a = i; erro
. . .
}
24

MAJS - JAVA

Ex 2:
static void desenha ( )
{
int i, j;
. . .
. . .
}
static int calcula ( )
{
int i, j;
. . .
. . .
}
i, j em desenha so variveis diferentes de i, j em
calcula.

25

MAJS - JAVA

VARIVEL GLOBAL

Varivel que declarada externamente podendo ser


acessada por qualquer funo (mtodos)

Ex:
public class Exemplo {
int i;
public static void main ( String args[ ] ) { }
static void desenha ( )
{
int j;
i = 0;
. . .
}
static void calcula ( )
{
int m;
i = 5;
. . .
}
}
26

MAJS - JAVA

Exemplo
static char minsculo( char ch )
{
If ( (ch >= A) && (ch <= Z))
ch += a - A;
return (ch);
}

O COMANDO RETURN

Causa a atribuio da expresso a funo,

Forando o retorno imediato ao ponto de chamada


da funo

27

MAJS - JAVA

Ex:
static char minsculo (char ch)
parmetro formal
{
If (( ch >= A) (ch <= Z))
return (ch + a-, A);
else
return (ch);
}
... main ( String args[ ] )
{
system.out.print ( Letra = , minsculo (A) );
parmetro real
}

28

MAJS - JAVA

Ex 2: Valor Absoluto
static int abs (int x)
{
return ( ( x < 0 ) ? -x : x );
}
...main (String args[ ] )
{
int numero;
String entrada;
entrada = ...showInputDialog (entre com um n > 0);
numero = Integer.parseInt(entrada);
numero = abs(numero);
. . .
. . .
}

29

MAJS - JAVA

PASSANDO VRIOS ARGUMENTOS

Freqentemente uma funo necessita de mais de


uma informao para produzir um resultado

Podemos passar para a funo mais de um


argumento

Ex 1:
static float rea_retngulo (float largura, float altura)
{
return (largura * altura);
}
Ex 2:
static float potncia (float base, int expoente)
{
int i; float resultado = 1;
If (expoente == 0)
return 1;
For (i = 1; i <= expoente; i++)
resultado *= base;
return resultado;
}
30

MAJS - JAVA

USANDO VRIAS FUNES


Calcular a seguinte sequncia:
S(x, n) = x/1! + x2/2! + x3/3! + ... + xn/ n!
Soluo:
static int fatorial (int n)
{
int i, resultado = 1;
for ( i = 1; i <= n; i ++)
resultado *= i;
return resultado;
}
static float potencia (float base, int expoente)
{
int i;
float resultado = 1;
If (expoente == 0)
return 1;
for (i = 1; i <= expoente; i++)
resultado *= base;
return resultado;
}
31

MAJS - JAVA

USANDO VRIAS FUNES

S(x, n) = x/1! + x2/2! + x3/3! + ... + xn/ n!


static float serie (float x, int n)
{
int i;
float resultado = 0;
for ( i = 1; i <= n; i++)
resultado += potncia( x, i ) / fat( i );
return resultado;
}

32

MAJS - JAVA

RECURSO

Baseado no princpio da induo


Chamada direta ou indireta da prpria funo

Exemplo:
Fatorial ( n )

=
=

n * Fatorial ( n 1 ), se n > 0
1, se n = 0.

static int fatorial ( int n ) {


if ( n == 0 )
return 1;
return ( n * fatorial ( n 1 ) );
}

33

MAJS - JAVA

RECURSO
Exemplo:
M*N

M + M + ... + M + M
----- N vezes ----

static int mult ( int m, int n ) {


int resultado = 0;
for ( int i = 0; i < = n; i++ )
resultado += m;
return resultado;

static int mult ( int m, int n ) {


if ( n == 0 )
return 0;
return ( m + mult (m, n -1 ) );
}

34

MAJS - JAVA

Entrada / Sada
package input;
import java.io.*;
public class Console {
final static BufferedReader console =
new BufferedReader (new InputStreamReader(System.in));
final static PrintStream terminal = System.out;
public static short readShort( ) {
try {
return Short.parseShort( console.readLine( ) );
} catch (IOException e) {
terminal.println(Erro I/O: digite novamente);
return readShort( );
} catch (NumberFormatException e) {
terminal.println(Erro: digite o formato correto);
return readShort( );
}
}
***
public static short readInt( ) {
***
}
}
35

MAJS - JAVA

Entrada / Sada

Exemplo de uso:
import input.*;
public class Exemplo {
public static void main(String args [ ] ) {
System.out.print("Digite um valor ");
short a = Console.readShort( );
System.out.println("Valor digitado = " + a);
}
}

36

MAJS - JAVA

Entrada / Sada

package input;
import javax.swing.*;
public class Janela {
static String line;
public static short readShort( ) {
try {
line = JOptionPane.showInputDialog(null,
Informe um valor short);
return Short.parseShort ( line );
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog( null,
Erro no formato: + line, Erro Entrada",
JOptionPane.ERROR_MESSAGE );
return readShort( );
}
}
***
public static short readInt( ) {
***
}
}

37

MAJS - JAVA

Entrada / Sada

Exemplo de uso:
import input.*;
import javax.swing.JOptionPane;
public class Exemplo {
public static void main(String args[ ]) {
short a = Janela.readShort( );
JOptionPane.showMessageDialog( null, Valor = + a );
System.exit(0);
}
}

38

MAJS - JAVA

Entrada / Sada
import java.util.*;
import java.text.*;
public class Exemplo {
public static void main(String args [ ] ) {
short a;
double b;
System.out.println("Informe um short int");
a = input.Console.readShort();
System.out.println("Informe um double");
b = input.Console.readDouble();
DecimalFormat a1 = new DecimalFormat("0.00");
System.out.println(a1.format(d));
}
}

39

MAJS - JAVA

Arranjos

estruturas de dados compostas por um nmero finito de


elementos do mesmo tipo:
Homogneas

um arranjo de tamanho N indexado de 0 a N-1:


um acesso invlido provoca a ocorrncia de uma
exceo do tipo IndexOutOfBoundsException

Definio:
T [ ] - arranjo de elementos do tipo T
int [ ] arranjo de inteiros
double [ ] arranjo de reais

40

MAJS - JAVA

Arranjos

criados dinamicamente em tempo de execuo:


o tamanho no faz parte do seu tipo

Exemplos:
int [ ] a = { 10, 20, 30 };
float [ ] [ ] b;
...
b = new float [ 4 ] [ 3 ];

Acesso aos elementos:


for ( int i = 0; i < a.length; i++ )
a[ i ] = 0;

41

MAJS - JAVA

Arranjos

Classe especial java.util:

Arrays

Operaes Comuns:
fill ( a1, v ): preenche a1 com o valor v;
fill (a1, i, f, v): preenche a1 de i at f com valor v;
equals (a1, a2): testar se a1 igual a a2;
sort( a1 ): ordena o vetor;

Exemplo:
public class Exemplo {
public static void main( String args [ ] ) {
int i;
int [ ] a = new int [ 5 ], b = new int [ 5 ];
for (i = 0; i < a.length; i++) a[i] = 5-i;
for (i = 0; i < b.length; i++) b[i] = i;
if (Arrays.equals(a, b))
System.out.println("Vetores iguais");
else
System.out.println("Vetores diferentes");
Arrays.fill(a, 5);
Arrays.fill(b, 2, 4, 6);
Arrays.sort(a);
}
}

42

MAJS - JAVA

Arranjos

Observao:
public class Exemplo {
public static void main(String args[ ] ){
int vetor, tamanho;
System.out.println(Informe o tamanho do vetor");
tamanho = readInt();
vetor = new int [ tamanho ];
...
}
}

43

MAJS - JAVA

Arranjos

Observao:
public class Exemplo {
public static void main( String args [ ] ){
int i, j;
int [ ] [ ] a = new int [ 2 ] [ ];
a[0] = new int[ 2 ];
a[1] = new int[ 3 ];
for (i = 0; i < a.length; i++)
for (j = 0; j < a[ i ].length; j++)
a [ i ][ j ] = i + j;
for (i = 0; i < a.length; i++) {
System.out.println();
for (j = 0; j < a[ i ].length; j++)
System.out.print(a[ i ][ j ] + " ");
}
}
}
44

Das könnte Ihnen auch gefallen