Exemplo Animated demo… Primitive data types Valores com casas

Propaganda
Exemplo
Tipos de Dados, Operadores e
Instruções de Controle de Fluxo
em Java
Slides_Java_2
public class CompInt
{
public static void main(String[ ] args)
{
double saldo, ganho, taxa;
saldo = 1000;
taxa = 0.09;
ganho = taxa * saldo;
saldo = saldo + ganho;
System.out.println( "Novo saldo: " + saldo );
}
}
Sistemas Informáticos
Animated demo…
Primitive data types
Type
Size
Range
boolean
1
true or false
char
16
Unicode 0 (\u0000) to Unicode 216 –1 (\uFFFF)
byte
8
-127 to +127
taxa = 0.09;
short
16
-32768 to +32767
ganho = taxa * saldo;
int
32
-2147483648 to +2147483647
saldo = saldo + ganho;
long
64
-9223372036854775808 to
+9223372036854775807
float
32
±3.40282347E+38 to ±1.40239846E-45
double
64
±1.79769313486231570e+308 to
±4.94065645841246544e-324
void
–
–
Código:
double saldo, ganho, taxa;
saldo = 1000;
Memória:
saldo
1000
1090
ganho
90
taxa
0.09
Valores com casas decimais
• Floating point numeric constant:
– Examples: 0.09
-0.034
345.6 .00
– Can also be written in scientific notation, e.g.:
2.0e2
(200.0)
-7.321e-3 (-0.007321)
double is default
• A floating point constant is a double by default.
• For example, the following generates a compiler
error:
float rate = 0.09;
• To force a numeric constant to be a float rather
than a double, use the suffice f:
float rate = 0.09f;
• Exercise: Which of the following numeric
constants are acceptable in Java?
9,87
.0
3.57*E2
3.57E+2
1
Variables
Vertical motion under gravity
• Variables must be initialized before being
used.
•
• Beware: if an integer type is increased above
its maximum value, it “wraps around” to the
minimum value, e.g:
•
int n = 2147483647; // largest int
n = n + 1;
System.out.println(n); // outputs -2147483648
public class Vertical {
public static void main(String[ ] args) {
// 1. Assign values of g, u and t
double g = 9.8;
// acceleration due to gravity
double s;
// vertical displacement
double t;
// time
double v;
// launch velocity
t = 6;
v = 60;
// 2. Compute the value of s
s = v*t – (g*t*t)/2;
// 3. Output the value of s
System.out.println( "s: " + s + " metres" );
}
}
Stone thrown vertically upward with initial
speed u, vertical displacement s, after time t,
is given by:
s = vt – gt2/2
where g is the acceleration due to gravity.
We want to write a program to compute the
displacement. The plan is:
1. Assign values of g, v and t
2. Compute the value of s
3. Output the value of s
Funções Matemáticas
• Para calcular potência: Math.pow(..,..)
– Exemplo: 53 = Math.pow(5,3)
• Para calcular raíz quadrada: Math.sqrt(..);
•
•
•
•
•
Seno de um ângulo: Math.sin(..);
Coseno de um ângulo: Math.cos(..);
Tangente de um ângulo: Math.tan(..);
Logaritmo de um número: Math.log(..);
Valor de ex: Math.exp(x);
Precedências…
• Usual precedence rules of arithmetic (* and /
have higher precedence than + and -)
• Parentheses have higher precedence.
• When operators have the same precedence,
they are evaluated from left to right.
• Exercises:
Evaluate the following Java expressions:
Answer: 2
1+4 / 4
2 * (1 + 2)/3
Answer: 2
5%3%2
Answer: 0
Exercises
• Write a program to convert a temperature in Celsius
read in from the user to Fahrenheit.
9
F = C + 32
5
In the second part, convert Fahrenheit to Celsius.
• Write a program to calculate x, where:
x=
− b + b 2 − 4ac
2a
Get the values of a,b and c from the user.
2
Increment and decrement
operators
Exercício lógico...
• Uma tartaruga está no ponto A e uma lebre está no
ponto B. Os pontos A e B estão distanciados de 64
kms. A lebre corre a 7 Kms/hora de B para A e a
tartaruga anda a 1Km/hora de A para B. Se ambos
os animais partirem ao mesmo tempo quantos Kms
terá que percorrer a lebre até encontrar a tartaruga?
• Escreva um programa em Java que resolva este
problema, considerando que a distância entre a lebre
e a tartaruga é de X Kms, que a lebre corre a L
Kms/hora, a tartaruga caminha a T Kms/hora e que
estas 3 variáveis inteiras (X,L,T) são lidas do teclado.
• Increment operator (++) is a shorthand way of
increasing a variable by 1, e.g:
c++;
// equivalent to c=c+1;
• Decrement operator (--) is a shorthand way of
decreasing a variable by 1.
x--;
// equivalent to x = x - 1;
• These operators can be used to increment or
decrement before or after the value is used, e.g:
a = ++b;
// increment b, before changing a
a = b++;
// set a to b and then increment b
• ++ and -- have higher precedence than arithmetic
operators
Assignment operators
x = a + Math.sqrt(b); // square root
z = Math.pow(a,b); // z = ab
n + 1 = n; // WRONG!
• Can also combine assignment with other
operators:
sum += x;
// equivalent to sum = sum + x
Cast operators
•
•
•
When an integer is divided by an integer, the decimal
part is truncated (i.e. it does integer division).
To prevent this we can convert an integer into a
double or float using a cast operator, e.g:
double x;
x = 5 / 2;
// x is 2.0
x = (float) 5 / 2;
// x is 2.5
x = 5 / (double) 2;
// x is 2.5
Also note:
x = 5 / 2.0;
// x is 2.5
Exemplo: qual o output?
public class DataTypes {
public static void main(String[] args) {
int j, k, m;
int d= 122;
j=d++;
System.out.println("j= " + j);
k=++d;
System.out.println("k= " + k);
m=--d;
System.out.println("m= " + m);
m= k % j;
System.out.println("m= " + m);
j= 5;
k= 3;
m= j/k;
System.out.println("m= " + m);
System.exit(0);
}
}
// j=122, d=123
j=122
d=124, k=124
k=124
d=123, m=123
m=123
m=124%122, =2
Execução de Ciclos em Java
m=5/3, =1
3
Repeating with for
Using the loop variable
• The for loop is used for executing the same chunk of
code a number of times.
for (int i = 1;
• Example 1:
for (int i = 1; i <= 3; i++)
System.out.print( “a” ); // prints aaa
{
• Example 2:
for (int i = 1; i <= 3; i++)
{
System.out.print( “a” );
System.out.print( “b” );
}
i <= 4;
i
5
4
3
2
1
System.out.print( i + " " );
}
do this
3 times
// prints ababab
Jumps right out of loop
Output:
1 2
3
4
Exemplos
class CountToTen {
public static void main (String args[]) {
int i;
for (i=1; i <=10; i = i + 1) {
System.out.println(i);
}
System.out.println("All done!");
}
}
class CountTenToZero {
public static void main (String args[]) {
int i;
for (i=10; i >0; i = i - 1) {
System.out.println(i);
}
System.out.println("All done!");
}
}
i++)
Exercícios
• Qual o output do seguinte código:
for (int i = 1; i <= 6; i++)
System.out.println( i*2);
System.out.println("End");
for (int i = 5; i > 0 ; i--)
System.out.println( i*2);
• Escreva um ciclo for que tenha o seguinte
output:
5 10 15 20 25 30 35 40 45 50
Cálculo Investimento
public class Invest
{
public static void main( String args[ ] )
{
double saldo = 50;
// saldo inicial
double taxa = 0.03; // taxa
Tabela: Fahrenreit to Celsius
// Print a Fahrenheit to Celsius table
class FahrToCelsius {
public static void main (String args[]) {
int fahr, celsius;
int lower, upper, step;
for (int year = 1; year <= 10; year++) {
saldo = saldo + taxa*saldo;
System.out.println( year + " " + Math.round( 100*saldo )/100. );
}
lower = 0;
// lower limit of temperature table
upper = 300; // upper limit of temperature table
step = 20; // step size
for (fahr=lower; fahr <= upper; fahr = fahr + step) {
celsius = 5 * (fahr-32) / 9;
System.out.println(fahr + " " + celsius);
} // for loop ends here
}
}
}
}
4
Square rooting with Newton
•
Newton’s method:
– technique for finding the square root of any
positive number
– Iterative procedure that uses only +, - and /
•
Structure plan:
1. Input a
2. Initialize x to 1 (the initial guess)
3. Repeat n times:
Replace x by (x + a / x) / 2
Print x
import essential.*;
public class MySqrt
{
// square-rooting with Newton
public static void main(String args[])
{
double a;
// number to be square-rooted
double x = 1; // guess at sqrt(a)
System.out.print( "Enter number to be square-rooted: " );
a = Keyboard.readDouble();
for (int i = 1; i <= 6; i++)
{
x = (x + a/x)/2;
System.out.println( x );
}
System.out.println( "Java's sqrt: " + Math.sqrt(a) );
}
}
Output of MySqrt
Enter number to be square-rooted: 2
1.5
1.4166666666666665
1.4142156862745097
1.4142135623746899
1.414213562373095
1.414213562373095
Java's sqrt: 1.4142135623730951
•
•
The value of x converges to a limit
Note that it is virtually identical to the value
returned by Java’s Math.sqrt method.
Exercício Suplementar
(Ex2.java)
• Escreva um programa em Java que leia o
valor N do teclado. N corresponde ao número
de alunos.
• Depois deve executar um ciclo de N
iterações onde em cada iteração deve pedir a
nota (1..20) do respectivo aluno.
• No final deve imprimir a média das N notas.
Exercícios
•
Calcule a soma de todos os números entre 1 e 100.
•
Apresente as raízes quadradas de todos os números entre 1 e
20.
•
Apresente os N valores correspondentes aos expoentes de a,
i.e. ab (b: 1 .. N).
Os valores de a e N são introduzidos pelo utilizador no teclado.
Exemplo: a=2, N=4
21= 2
22= 4
23= 8
24= 16
Factorials!
public class MyFactorial{
public static void main(String[] args){
int n;
long fact = 1;
System.out.print( "Enter n: " );
n = Keyboard.readInt();
System.out.println( n );
for (int k = 1; k <= n; k++) {
fact = k * fact;
System.out.println( k + "!= " + fact );
}
}
}
• What is the output if the user enters 5?
• Change the program so that only the final answer is
printed out, and not the intermediate values.
5
Math methods
Characters
• Primitive data type char holds a single
character, e.g.:
char c = 'a';
• Each character has a unique Unicode number,
e.g. ‘a’ is 97.
• Can use a for loop to print the letters of the
alphabet:
for(char c = 'a'; c <= 'z'; c++)
System.out.println(c);
'\n' (newline)
ln( x + x 2 + a 2 )
In Java:
x2= Math.pow(x,2);
double first = Math.log(x + x*x + a*a);
[e3t + t 2 sin( 4t )] cos 2 (3t )
• Special characters indicated with backslash:
'\t' (tab)
• Standard Java Math class contains methods useful in
scientific calculations (e.g. ,sqrt, cos, exp, floor, log).
• Examples using Math methods:
'\\' (backslash)
In Java:
(Math.exp(3*t) + t*t*Math.sin(4*t))
* (Math.pow(Math.cos(3*t), 2));
1
ln( a b + y + 3 x + sin( a ) + cos(b))
double d = 1/(Math.log(Math.pow(a,b) + Math.sqrt(y) + Math.pow(x,1/3) +
Math.sin(a) + Math.cos(b)));
Exemplos de conversão de
fórmulas matemáticas para Java
1
x + y + (a b ) c
double d = 1 / (x+y + Math.pow(Math.pow(a,b),c));
1
1
+ (ab) 2
x+ y
y = υt sin(α ) −
gt 2
2
double d = 1 / (x+y) + Math.sqrt(a*b);
double y = v*t*Math.sin(a)- (g*t*t)/2;
Ficheiros em Java: essential
Ficheiros em Java
FileIO f1 = new FileIO( “input.txt", FileIO.READING);
...
double n = f1.readDouble();
int i = f1.readInt();
f1.closeFile();
FileIO f2 = new FileIO( “output.txt",FileIO.WRITING);
int n=...;
f2.print(n);
f2.println(“the end...”),
...
f2.closeFile();
6
Operações Leitura/Escrita
print(String message)
println(String message)
double
float
int
String
long
readDouble()
readFloat()
readInt()
readLine()
readLong()
Calcular média números de
um ficheiro
import essential.*;
public class ReadNums {
public static void main(String args[])
{
FileIO f1 = new FileIO( "nums.txt", FileIO.READING );
double n = f1.readDouble();
double sum = 0;
double x, average;
for (int i = 1; i <= n; i++) {
x = f1.readDouble( );
sum = sum + x;
}
average = sum / n;
System.out.println( "Media= " + average );
}
}
Reading data from a text file
• Say you have a file nums.txt which contains the
following values:
10 3.1 7.2 4.5 9.9 6.0 7.9 3.7 9.2 6.5 3.9
• The first value (10) indicates how many numbers there
are.
• We want to find the average of the 10 numbers.
• We can use the FileIO class (in the essential package)
to read in values from a text file.
• Example:
FileIO f1 = new FileIO(“nums.txt”, FileIO.READING);
double d = f1.readDouble();
Escrita num ficheiro
import essential.*;
public class FileTest
{
public static void main(String args[])
{
FileIO f1 = new FileIO( "output.txt", FileIO.WRITING );
for(int i=0; i < 100;i++)
f1.print((double)i+" ");
}
}
Mais um exemplo com Ficheiros
import essential.*;
public class ReadWriteNums
{
public static void main(String args[])
{
double sum, avg;
int x,n;
sum = 0;
FileIO f1 = new FileIO( "nums.txt", FileIO.READING );
FileIO f2 = new FileIO( "output.txt", FileIO.WRITING );
n = f1.readInt();
f2.print(n+" ");
System.out.println("O ficheiro tem "+ n +" numeros");
System.out.println("===============================");
for (int i = 1; i <= n; i++)
{
x = f1.readInt( );
f2.print(x+" ");
System.out.println("leu o numero "+x+" do ficheiro...");
sum += x;
}
avg = sum / n;
System.out.println( "Media dos numeros: " + avg );
f2.println(avg);
Estrutura de controle: if-else
}
}
7
Estrutura de selecção: if
• Selecção simples
– Implementada pela instrução: if
– Sintaxe da instrução:
Estrutura de selecção: if-else
• Selecção em alternativa
– Implementada pela instrução: if - else
– Sintaxe da instrução:
if (condição)
instrução;
– A condição é uma expressão lógica.
– Caso o resultado da condição seja true a instrução
é executada.
– Se for false a instrução não é executada.
if (condição)
instrução 1;
else
instrução 2;
– Se o resultado da condição for true a instrução 1 é
executada; se for false é executada a instrução 2.
Exemplo: estrutura if
import essential.*;
public class Age
{
public static void main(String[] args)
{
int idade;
System.out.print( “Que idade tem? " );
idade = Keyboard.readInt();
if (idade < 20)
System.out.println( “ainda é teenager….” );
}
}
Spinning a coin
public class SpinCoin {
public static void main(String[ ] args)
{
double x = Math.random();
if (x < 0.5)
System.out.println( “Cara" );
else
System.out.println( “Coroa" );
}
}
The if-else statement
if (idade < 30) {
System.out.println(“é um jovem…" );
}
else{
System.out.println( “é um cota…" );
}
• What will be the output if the user enters 25? And 30?
• Can have multiple statements in block markers after if
or else.
<=
>
>=
• Other relational operators: == !=
Exemplo: estrutura if-else
import essential.*;
public class ParOuImpar {
public static void main (String args[]) {
int num;
System.out.print (“Qual o número ? “);
num = Keyboard.readInt ();
num = num % 2;
if (num == 0)
System.out.println (“Número é par”);
else
System.out.println (“Número é ímpar”);
}
}
8
Exercício: Notas2.java
Escreva um programa que leia de um ficheiro
as notas obtidas numa cadeira (0..20).
Selecção de Alternativas
• Seleccionar entre várias alternativas
– Ex: Seleccionar uma de três alternativas em função do valor
de uma variável. Se nenhuma se verificar deve fazer a
instrução 4.
Deve indicar o número de alunos que fizeram
a cadeira e o número de alunos que
chumbaram.
if (num >= 1 && num <= 10)
instrução 1;
else if (num > 10 && num <= 20)
instrução 2;
else if (num > 20 && num <= 30)
instrução 3;
else instrução 4;
Exercício 1
Exercício 2
• Escreva o seguinte programa:
• Escreva o seguinte programa:
–
–
–
–
–
Pede ao utilizador um nº (inteiro)
Se esse nº for igual a 1, deve imprimir “Benfica”
Se for igual a 2, deve imprimir “Sporting”
Se for igual a 3, deve imprimir “Porto”
Caso contrário, deve imprimir “Outra equipa...”
– Pede ao utilizador um nº (inteiro) idade
– Se a idade for menor do que 6 deve imprimir
“Isento de Bilhete”
– Se a idade for maior do que 6 mas menor do que
12 deve imprimir “Bilhete de Criança”
– Se for superior a 12 mas menor do que 65 deve
imprimir “Bilhete Normal”
– Caso contrário, deve imprimir “Bilhete de 3ª idade”
Exercício (Notas3.java)
Exercise
Escreva um programa que leia de um ficheiro as
notas obtidas numa cadeira. Consoante a nota
indicada deve apresentar as seguintes mensagens:
• Work through the following program by hand.
• Draw up a table of the values of i, j and m to
show how their values change while the
program executes.
Se o aluno teve entre 0 e 5 é um aluno Mau;
Se o aluno teve entre 6 e 9 é Sofrível;
Se teve entre 10 e 13 é Mediano;
Entre 14 e 16 é um aluno Bom;
Entre 17 e 19 é um aluno Muito Bom;
Se teve 20 é um autêntico Daniel...;
int m;
int i = 1;
for (int j = 3; j <= 5; j++) {
i++;
if (i == 3) {
i += 2;
m = i + j;
}
}
9
Logical operators & Boolean
variables
Logical operators
• Logical expressions can be combined with
each other using logical operators.
• Consider the quadratic equation:
ax2 + bx + c = 0
• It has real roots, given by –b/2a, provided
that:
b2 – 4ac = 0 ^ a ≠ 0
• Translates into the following Java:
if ((b*b – 4*a*c) == 0 && (a != 0))
x = - b/(2*a)
• Logical operators:
– AND (&&)
– OR (||)
– NOT (!)
• Java has a primitive data type called boolean, which
can take on the value true or false.
• Example:
boolean d = true;
d = (b*b) < (4*a*c); (b=4;a=1;c=2; d=?)
• Can print out the value of a boolean, e.g:
System.out.println(d);
// true or false?
System.out.println( 2*2 == 4);
Operadores Lógicos
// prints true
Selecção Múltipla: switch
• Selecção múltipla: switch
AND
&&
0 && 0
0 && 1
1 && 0
1 && 1
OR
=0
=0
=0
=1
||
0 || 0
0 || 1
1 || 0
1 || 1
NOT
=0
=1
=1
=1
!
!0=1
!1=0
Selecção Múltipla: switch
• Selecção múltipla: switch
– A expressão utilizada numa instrução switch terá que
ter um resultado inteiro ou caracter.
– A instrução break é colocada no fim das instruções
relativas a cada case. Tem como função provocar o fim
do switch.
– A opção default (pode não existir) é executada se o
valor da expressão não for igual a nenhum dos valores
utilizados no switch.
– A instrução switch permite escolher uma de várias
alternativas e tem a seguinte sintaxe:
switch (expressão) {
case valor1 : instrução 1; break;
case valor2 : instrução 2; break;
...
case valorn : instrução n; break;
default : outra instrução; break;
}
The switch statement
System.out.println( "Enter your choice (any integer)" );
int choice = Keyboard.readInt();
switch (choice)
{
case 1:
System.out.println( "Do this" );
break;
case 2:
case 3:
System.out.println( "Do that" );
break;
default:
System.out.println( "Do the other" );
}
10
Exemplo com o Switch
// Escreva um programa que leia um caracter (letra) e o classifique como
consoante ou vogal.
class VogaisConsoantes {
public static void main(String[] args) {
char c;
System.out.print("Introduza a Letra: ");
c = Keyboard.readChar();
switch(c) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
System.out.println("A letra " + c + " é uma vogal");
break;
default:
System.out.println("A letra " + c + " é uma consoante");
}
}
}
Exemplo: switch
Versão com if-else
// Escreva um programa que leia um caracter (letra) e o classifique como consoante ou
vogal.
class VogaisConsoantes {
public static void main(String[] args) {
char c;
System.out.print("Introduza a Letra: ");
c = Keyboard.readChar();
if(c == ‘a’ || c == ‘e’ || c == ‘i’ || c == ‘o’ || c == ‘u’)
System.out.println(“é uma vogal…”);
else
System.out.println(“é uma consoante…”);
}
}
Exercício para a Aula
Dados dois operandos (x e y) e um operador (op) determinar o resultado (x op y)
char op;
double result, x, y;
op = Keyboard.readChar();
switch (op) {
case ‘+’ : result = x + y; break;
case ‘-’ : result = x - y; break;
case ‘*’ : result = x * y; break;
case ‘/’ : if (y != 0){
result = x / y;}
else {
System.out.println (“Atenção! Divisão por zero”);
}
break;
}
Exercício
•
•
Escreva um programa que apresente no
écrân a estação do ano de um determinado
mês (pedido ao utilizador).
Escreva uma solução com if-else e outra
solução com selecção múltipla (switch).
Escreva um programa que associe um valor
qualitativo a uma nota quantitativa.
1=Mau
2=Medíocre
3=Suficiente
4=Bom
5=Excelente
(a) Versão A, usando switch
(b) Versão B, usando if-else
Instruções de Repetição: while
• Repetição: while
– Implementada pela instrução: while
– Sintaxe da instrução:
while (condição)
instrução;
– A instrução começa por calcular o valor da condição. Se der true é
executado a instrução ou bloco de código, após o qual a condição
é novamente avaliada. Esta repetição será mantida enquanto o
valor da condição se mantiver true. Quando tal não acontecer a
instrução termina.
11
Exemplo: ciclo while
Instruções de Repetição: while
• Repetição: ciclos while
Escrever no ecrã todos os inteiros entre 1 e 5:
– A condição é avaliada antes da execução da instrução
a repetir, pelo que, se a expressão der false logo no
ínicio a instrução nunca chega a ser executada.
public class WhileDemo {
public static void main(String args[]) {
int i = 1;
while (i <= 5) {
System.out.println (i);
i ++;
}
}
}
– Há que ter em conta a possibilidade de criação de
ciclos infinitos (situação esta que deve ser evitada)
Deve haver o cuidado de incluir instruções que, em alguma situação, alterem
o valor da condição de controle do ciclo, de modo a que este termine.
Exemplo: while
import essential.*;
// Efectuar a soma dos valores até ultrapassar 100...
public class SomaDigitos {
public static void main(String args[]) {
int num;
int soma = 0;
while (soma < 100) {
System.out.println (“Escreva um número: “);
num = Keyboard.readInt();
soma = soma + num;
}
System.out.println (“Soma dos números=” + soma);
}
}
Exercícios
1- Escreva um programa que some todos os
números introduzidos no teclado, até o
utilizador inserir um número negativo. No
final deverá imprimir a média desses
números.
2- Escreva um programa que vá lendo do
teclado um conjunto de números até o
utilizador inserir um número negativo. No
final deve imprimir o maior desses números.
Exercício 3
• Escreva um programa que leia valores inteiros de um
ficheiro e que no final do programa imprima no écrân
o valor mais alto.
• O programa termina quando chegar ao final do
ficheiro.
Exercício 4
•
Escreva um programa que leia do teclado
um n.º inteiro positivo, e devolva a soma
dos seus dígitos.
Exemplo: se o n.º for 1234, o programa
deverá devolver 10 (1+2+3+4).
FileIO f = new FileIO( "input.txt", FileIO.READING);
while( f.isEof() == false) // enquanto nao chegar ao final do ficheiro
val = f.readInt();
....
12
Ciclos do-while
• Repetição: do-while
– Implementada pela instrução: do-while
– Sintaxe da instrução:
do
instrução;
while (condição);
– Começa por executar a instrução, após o que calcula o
valor da condição. Se der true a instrução é executada
novamente.
– Esta repetição será mantida até que o valor da condição
passe a false.
Exemplo: do-while
public class DoWhileDemo {
public static void main(String args[]) {
int i = 1;
do {
System.out.println (i);
++ i;
} while (i <= 5)
}
}
13
Download