Beruflich Dokumente
Kultur Dokumente
Forma Geral
public class Introducao {
public static void main (String args[]) {
System.out.println(Oi!");
}
}
MAJS - JAVA
Objeto de Sada
System.out
Exibe as informaes na janela de comando
1
2
3
MAJS - JAVA
Objeto de Sada
CARACTERES DE CONTROLE
\n
nova linha
\renter
\t
tabulao (tab)
\b
retrocesso
\
aspas
\\
barra
MAJS - JAVA
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
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
exemplo:
int idade;
idade = 30;
String nome = Jose;
MAJS - JAVA
DECLARANDO VARIVEIS
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
obs:
sensvel ao caso:
peso <>
Peso
<>
pEso
Palavras Chave:
static
int
if
while
etc
10
MAJS - JAVA
Operadores
Operador
() []
! ++ -- + - (tipo)
* / %
+ - (binrio)
>> <<
< <= >= >
== !=
||
&&
?:
= += -= *= /= %=
>>= <<= &= |= ^=
11
MAJS - JAVA
Operadores
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 );
13
MAJS - JAVA
Observao
JOptionPane.ERROR_MESSAGE
JOptionPane.WARNING_MESSAGE
JOptionPane.QUESTION_MESSAGE
JOptionPane.INFORMATION_MESSAGE
JOptionPane.PLAIN_MESSAGE
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
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
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
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
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
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
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
MAJS - JAVA
32
MAJS - JAVA
RECURSO
Exemplo:
Fatorial ( n )
=
=
n * Fatorial ( n 1 ), se n > 0
1, se n = 0.
33
MAJS - JAVA
RECURSO
Exemplo:
M*N
M + M + ... + M + M
----- N vezes ----
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
Definio:
T [ ] - arranjo de elementos do tipo T
int [ ] arranjo de inteiros
double [ ] arranjo de reais
40
MAJS - JAVA
Arranjos
Exemplos:
int [ ] a = { 10, 20, 30 };
float [ ] [ ] b;
...
b = new float [ 4 ] [ 3 ];
41
MAJS - JAVA
Arranjos
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