Pertemuan 1 sd. 5 (10 JP)
3.1. Memahami penggunaan data dalam algoritma dan konsep algoritma pemrograman.
4.1. Menggunakan algoritma pemrograman untuk memecahkan permasalahan.
1. Persiapan Instalasi JDK
2. Menjalankan Java dengan Editor NotePad++
class Apples {
}
class Apples {
public static void main (String args []){
}
}
class Apples {
public static void main (String args []){
System.out.println(“Hello youtube!”);
}
}
D:
Cd \
dir
Cd test
Dir
javac youtube.java
dir
java youtube
4. Hello youtube!
class apples{
}
c. Di dalam class ada method, contoh method bernama bakecake, dimana didalamnya ada instruksi instruksi, misalnya…
class apples{
void bakecake(){
mix batter;
put in oven;
eat the fine cake;
}
}
d. Main method adalah paling dasar dalam java, contohnya..
class apples{
public static void main(String args[]){
System.out.println(“Hello youtube”);
}
}
e. Penjelasan dari program dasar java ini adalah…
nama class : class apples{}
method header : public static void main(String args[]){}
method body : System.out.println(“Hello youtube”);
5. Variable
Double tuna;
Tuna = 5.28;
System.out.print(tuna);
Lihat hasilnya… ketik lagi yang berikut.
Double tuna;
Tuna = 5.28;
System.out.print(“I want “);
System.out.print(tuna);
System.out.println(“ movies”); lihat hasilnya lalu ketik lagi…
System.out.print(“movies“);
6. Getting User Input, mengambil data dari keyboard, kita impor utility Scanner.
import java.util.Scanner;
class apples{
public static void main(String args[]){
Scanner namaku = new Scanner(System.in);
System.out.println(namaku.nextLine());
//untuk data string .nextLine
}
}
7. Kalkulator sederhana
Import java.util.Scanner;
class apples{
public static void main(String args[]){
Scanner jono = new Scanner(System.in);
double angka1, angka2, tambah;
System.out.println(“Masukkan angka pertama : “);
angka1 = jono.nextDouble();
// nextDouble untuk data jenis angka (value)
System.out.println(“Masukkan angka kedua : “);
angka2 = jono.nextDouble();
tambah = angka1 + angka2;
System.out.println(“Jika dijumlahkan : “+tambah);
}
}
8. Operator matematik, ada beberapa operator matematik seperti +, -, *, /, % yang dapat digunakan. Contoh berikut :
import java.util.Scanner;
class apples{
public static void main (Stiring args[]){
Scanner masuk = new Scanner(System.in);
int angka1, angka2, hasil;
angka1 = 11;
angka2 = 3;
hasil = angka1 + angka2;
System.out.println(hasil);
hasil=angka1 / angka2;
}
}
Pertemuan 2
9. Mendapatkan Input dari Keyboard menggunakan BufferedReader.
Jika sebelumnya kita mendapatkan input dari keyboard menggunakan import.util.Scanner, sekarang menggunakan input.java.io.*
Disamping itu menambahkan statement :
BufferedReader dataIn = new BufferedReader(new InputStreamReader( System.in) );
Dan variabel String temporary untuk input, fungsi readLine(), dan blok try-catch seperti berikut:
try{
String temp = dataIn.readLine();
}
catch( IOException e ){
System.out.println(“Error in getting input”);
}
Berikut contoh lengkap source codenya, simpan dengan nama file DataDariKeyboard.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class DataDariKeyboard {
public static void main( String[] args ){
BufferedReader dataIn = new BufferedReader(new
InputStreamReader(System.in) );
String nama = "";
System.out.print("Silahkan Masukkan Nama Anda:");
try{
nama = dataIn.readLine();
}catch( IOException e ){
System.out.println("Salah!");
}
System.out.println("Assalamualaikum " + nama +"!");
}
}
10. Menggunakan JOptionPane.
Cara lain adalah menggunakan class JOptionPane dari package javax.swing dan memunculkan dialog box standart yang lebih menarik bagi user. Contoh buat class bernama DataDariJOption
import javax.swing.JOptionPane;
public class DataDariJOption{
public static void main( String[] args ){
String nama = "";
nama = JOptionPane.showInputDialog("Masukkan Nama Anda : ");
String pesan = "Assalamualaikum " + nama + "!";
JOptionPane.showMessageDialog(null, pesan);
}
}
LATIHAN
1. Buatlah 3 input kata menggunakan BufferedReader dan tampilkan ke3 kata tersebut menjadi sebuah kalimat. Contoh tampilan program :
Masukkan kata pertama : Kami
Masukkan kata kedua : Belajar
Masukkan kata ketiga : Java
Kami Belajar Java
2. Buatlah hal yang sama menggunakan JOptionPane untuk 3 input kata, dan tampilan ke 3 kata tersebut menjadi sebuah kalimat seperti tampilan di atas.
Pertemuan 3
11. Tipe Dasar Variabel Data.
a. Data primitive
(1) byte : data 8-bit. minimum -128 atau (-2^7), maksimum 127 atau (2^7)-1
Contoh : byte a = 100;
byte b = -58;
(2) short : data 16-bit, minimum -32.768 atau (-2^16), maksimum 32.767 atau (2^16)-1
Contoh : short c = 10000;
short d = -20000;
(3) int: data 32-bit. minimum - 2,147,483,648 atau.(-2^31), maksimum 2,147,483,647 atau.(2^31 -1)
Contoh : int e = 100000;
int f = -200000;
(4) long: data 64-bit. minimum -9,223,372,036,854,775,808 atau (-2^63), maksimum 9,223,372,036,854,775,807 atau (2^63 -1)
Contoh : long g = 100000L;
long h = -200000L;
(5) float: data 32-bit dengan presisi single floating point, sehingga tidak pernah untuk hitungan presisi seperti keuangan.
Contoh : float i = 234.5f;
(6) double: data 64-bit dengan presisi double floating point, juga tidak pernah untuk hitungan presisi seperti keuangan.
Contoh : double j = 234.56d;
(7) boolean: data 1-bit informasi dengan dua kemungkinan yaitu true dan false.
Contoh : boolean lulus = false;
(8) char: data 16-bit UNICODE character. Minimum '\u0000' atau 0 dan maksimum '\uffff' atau 65,535.
Contoh : char A = ‘A’;
b. Data reference, dibuat menggunakan konstruktor class
Contoh : Binatang binatang = new Binatang(“Singa”);
12. Tipe Variabel Data.
a. Variabel local.
Dideklarasikan dalam method, constructor dan block. Contoh :
public class Test{
public void pupUsia(){
int usia = 0;
usia = usia + 7;
System.out.println("Umur Jono adalah : " + usia);
}
public static void main(String args[]){
Test test = new Test();
test.pupUsia();
}
}
b. Variabel Instance.
Dideklarasikan dalam class, diluar method, constructor atau block. Contoh :
import java.io.*;
public class Karyawan{
// variabel istance ini nampak untuk class turunannya.
public String nama;
// variabel gaji nampak hanya dalam class Karyawan.
private double gaji;
// Variabel Nama ditugaskan di constructor.
public Karyawan (String karNama){
nama = karNama;
}
// Variabel gaji bertype nilai.
public void setGaji(double karGaji){
gaji = karGaji;
}
// Method ini akan mencetak rincian karyawan.
public void cetakKar(){
System.out.println("Nama : " + nama );
System.out.println("Gaji :" + gaji);
}
public static void main(String args[]){
Employee karSatu = new Karyawan("Ransika");
karSatu.setGaji(1000);
karSatu.cetakKar();
}
}
c. Variabel Class/Static.
Dideklarasikan dalam class, diluar method, constructor atau block. Contoh :
import java.io.*;
public class Karyawan2{
// variable gaji adalah sebuah variabel private static
private static double gaji;
// DEPARTMENT adalah konstanta
public static final String DEPARTMENT = "Development ";
public static void main(String args[]){
gaji = 1000;
System.out.println(DEPARTMENT+"average salary:"+gaji);
}
}
TUGAS: X MM 1, SELASA 11-NOP-2014, JAM 7-8
X MM 2, RABU 12-NOP-2014, JAM 1-2
Java Applet adalah aplikasi java yang bisa disisipkan kedalam halaman HTML. Java applet bisa berjalan pada web browser yang telah mendukung java seperti mozilla, IE, dan chrome. Applet dirancang untuk berjalan ‘remotely‘ pada browser client, sehingga ada beberapa keterbatasan. Secara default, applet tidak bisa mengakses resource pada komputer lokal. Applet biasanya digunakan untuk membuat website lebih dinamis dan menghibur.
1. Contoh membuat Applet dengan tampilan “Assalamu’alaikum”
import java.awt.*;
import java.applet.*;
/* <applet code = "CobaAppletSalam" width = 300 height = 300> </applet> */
public class CobaAppletSalam extends Applet {
public void paint (Graphics g) {
g.drawString("Hello world!", 80, 25);
}
}
2. Simpan dengan nama CobaAppletSalam.java. Dan untuk menjalankan di prompt, dengan perintah berikut :
D:\>appletviewer CobaAppletSalam.java
Untuk kembali ke CMD tutup terlebih dahulu appletviewer.
3. Latihan membuat gambar Lampu seperti berikut.
import java.awt.*;
import java.applet.*;
/* <applet code="Lamp" width =600 height = 800></applet> */
public class Lamp extends Applet {
public void paint(Graphics g) {
// template untuk membuat applet
g.fillRect(50,250,290,290);
// dasar lampu berupa segiempat
g.drawLine(125,250,125,160);
g.drawLine(175,250,175,160);
// garis tegak dua buah
g.drawArc(85,157,130,50,-65,312);
g.drawArc(85,87,130,50,62,58);
// sudut lingkaran
g.drawLine(85,177,119,89);
g.drawLine(215,177,181,89);
// garis penghubung sudut lingkaran
g.fillArc(78,120,40,40,63,-174);
g.fillOval(120,96,40,40);
g.fillArc(173,100,40,40,110,180);
// memberi variasi dalam kap lampu
}
}
Soal Ulangan Harian
1. Symbol flowchart yang digunakan untuk menyatakan mulai atau selesai disebut
A. Terminator C. Input/Output
B. Process D. Selection/Decision
E. Pre-defined Data
2. Macam – macam dari tipe data dasar adalah sebagai berikut, kecuali
A. Integer C. Char
B. Real D. Boolean E. Array
3. Tipe data untuk menyatakan karakter data tunggal adalah
A. Integer C. Char
B. Real D. Boolean E. Array
4. Berikut ini merupakan keyword (kata kunci) pada java, kecuali
A. Import C. super
B. unit D. extends E. new
5. Nama yang diciptakan oleh pemrogram digunakan untuk memberi nama kelas atau variable pada java disebut
A. keyword C. identifier
B. character D. literal E. variable
6. Aplikasi java yang dapat disisipkan ke halaman html adalah…
A. applet C. bufferedReader
B. swing D. streamReader E. lang
STRUKTUR KONTROL
1. if – else
2. if – ilse if
3. if – else if – else
4. switch – case – break – default
import java.util.Scanner;
public class Uji_switchcase{
public static void main (String args[]){
System.out.print("Masukkan Nilai anda : ");
Scanner gayung = new Scanner(System.in);
int Nilai ;
Nilai = gayung.nextInt();
switch (Nilai) {
case 4:
System.out.println("Keterangan : Sangat Baik");
break;
case 3:
System.out.println("Keterangan : Baik");
break;
case 2:
System.out.println("Keterangan : Cukup");
break;
case 1:
System.out.println("Keterangan : Kurang");
break;
default:
System.out.println("Maaf, nilai anda salah!!");
} } }
TUGAS :
BUATLAH PROGRAM UNTUK MENAMPILKAN NAMA BULAN (JANUARI, FEBRUARI DST) JIKA ANDA MEMASUKKAN ANGKA 1 SD 12. SELAIN ANGKA ITU BERI PESAN KESALAHAN…
Nama class : Uji_bulan.java
5. while – loop (untuk perulangan)
contoh : menampilkan angka 1 sd 10
hasil : 1 2 3 4 5 6 7 8 9 10
1
2
3
4
public class Uji_loop1{
public static void main (String [] args){
int angka = 1;
while (angka<=10){
System.out.print(angka+", ");
angka=angka+1;
}
}
}
TUGAS 1:
BUATLAH DERET ANGKA 2, 4, 6, 8, 10, 12,
Nama Class : Uji_loop2.java
Tugas 2 :
Buatlah deret angka : 200, 175, 150, 125, 100, 75, 50, 25, 0
Nama class : Uji_loop3.java
Tugas Kompleks :
public class Ayam{
public static void main (String args []){
int mati;
int ayam=100;
String teks ="tek kotek kotek kotek... anak ayam turun ";
for (mati = 1; mati <=100; mati++){
if (ayam<=1){
System.out.println(teks+ayam+" mati 1 tinggal induknya ");
break;
}
System.out.println(teks+ayam+" mati 1 tinggal "+(ayam-1));
ayam--;
}
}}
Pertemuan ke
Materi :
Pernyataan Break
1. Break tidak berlabel
a. Untuk menghentikan perintah switch
b. Untuk menghentikan for, while, dan do-while
Contoh :
String nama[] = {“Yono”, “Yayuk”, “Yahya”, “Iin”, “Wisnu”, “Susi”}
String cariNama = “Wisnu”;
boolean ketemuNama=false;
for (int i=0, i<nama.lengh; i++0{
if(nama[i].equals(cariNama)){
ketemuNama=true;
break;
}}
If (ketemuNama){
System.out.println(cariNama+ “ ditemukan!”);
}
else{
System.out.println(cariNama+ “ tidak ditemukan!”);
}
Buat nama class Break_komp1mm2.java,Break_laptop1mm2
Dalam program ada nama panggilan yang membuat
2. Break berlabel
a. Menghentikan pernyataan yang diberi label
Pernyataan Continue
1. Continue tidak berlabel
a.
Pernyataan Percabangan
1. Pernyataan Break
Pernyataan break memiliki dua bentuk: tidak berlabel (unlabeled) dan berlabel (labeled).
• Pernyataan Break Tidak Berlabel
Definisi :
Pernyataan break tidak berlabel (unlabeled) digunakan untuk menghentikan jalannya pernyataan switch. Selain itu pernyataan break unlabeled juga bisa digunakan untuk menghentikan pernyataan-pernyataan for, while atau do-while loop.
Contoh Program :
public class BelajarJava {
public static void main(String[] args) {
String names[] = {"Mojo", "Tika"};
String searchName = "Mojo";
boolean foundName = false;
for( int i=0; i< names.length; i++ ){
if( names[i].equals( searchName )){
foundName = true;
break;
}
}
if( foundName ){
System.out.println( searchName + " found!" );
}
else{
}
}
}
• Pernyataan Break Berlabel
Definisi:
Bentuk label dari pernyataan break akan menghentikan pernyataan di luarnya, dimana sebelumnya harus diberikan label yang sudah di spesifikasikan pada program pada pernyataan break. Program berikut ini akan mencari nilai dalam array dua dimensi.
Terdapat dua pengulangan bersarang (nested loop). Ketika sebuah nilai ditemukan break akan menghentikan pernyataan yang diberi label searchLabel yang terletak di luar pernyataan for loop.
Contoh program :
public class BelajarJava {
public static void main(String[] args) {
int[][] numbers = {{1, 2, 3},
{4, 5, 6},
{7, 8, 9}};
int searchNum = 5;
boolean foundNum = false;
searchLabel:
for( int i=0; ifor( int j=0; jif( searchNum == numbers[i][j] ){
foundNum = true;
break searchLabel;
}
}
}
if( foundNum ){
System.out.println( searchNum + " found!" );
}
else{
}
}
}
2. Pernyataan Continue
Pernyataan continue memiliki dua bentuk: berlabel dan tidak berlabel. Anda dapat
menggunakan pernyataan continue untuk melanjutkan pengulangan yang sedang
dijalankan oleh pernyataan for, while, atau do- while loop.
• Pernyataan Continue Tidak Berlabel
Definisi :
Bentuk pernyataan continue tidak berlabel (unlabeled) akan melewati bagian pernyataan setelah pernyataan ini dituliskan dan memeriksa eksepresi logika (boolean) yang mengkontrol pengulangan. Jika ekspresi logika (boolean) masih bernilai true, maka pengulangan tetap dilanjutkan. Pada dasarnya pernyataan ini akan melanjutkan bagian pengulangan pada pernyataan loop.
Contoh Program :
public class BelajarJava {
public static void main(String[] args) {
String names[] = {"Mojo", "Tika"};
int count = 0;
for( int i=0; iif( !names[i].equals("Mojo") ){
continue; //skip next statement
}
count++;
}
System.out.println("There are " + count + " Mojo in the list");
}
}
• Pernyataan Continue Berlabel
Definisi :
Bentuk pernyataan continue berlabel (labeled) akan melanjutkan pengulangan yang sedang terjadi dan dilanjuti ke pengulangan berikutnya dari pernyataan pengulangan yang diberi label (tanda).
Contoh Program :
public class BelajarJava {
public static void main(String[] args) {
outerLoop:
for( int i=0; i<5 br="" i="">for( int j=0; j<5 br="" j="">System.out.println("Inside for(j) loop"); //message1
if( j == 2 ) continue outerLoop;
}
System.out.println("Inside for(i) loop"); //message2
}
}
}
3. Return
Definisi :
Pernyataan return digunakan untuk keluar dari sebuah method. Pernyataan return memiliki dua bentuk: memberikan sebuah nilai, dan tidak memberikan nilai.
Untuk memberikan sebuah nilai, cukup berikan nilai (atau ekspresi yang menghasilkan sebuah nilai) sesudah kata return. Contohnya,
return ++count;
atau
return "Hello";
Tipe data dari nilai yang diberikan harus sama dengan tipe dari method yang dibuat. Ketika sebuah method void dideklariskan, gunakan bentuk return yang tidak memberikan nilai.
Contohnya,
return;
The if-then and if-then-else Statements
The if-then Statement
The if-then statement is the most basic of all the control flow statements. It tells your program to execute a certain section of code only if a particular test evaluates to true. For example, the Bicycle class could allow the brakes to decrease the bicycle's speed only if the bicycle is already in motion. One possible implementation of the applyBrakes method could be as follows:
void applyBrakes() {
// the "if" clause: bicycle must be moving
if (isMoving){
// the "then" clause: decrease current speed
currentSpeed--;
}
}
If this test evaluates to false (meaning that the bicycle is not in motion), control jumps to the end of the if-then statement.
In addition, the opening and closing braces are optional, provided that the "then" clause contains only one statement:
void applyBrakes() {
// same as above, but without braces
if (isMoving)
currentSpeed--;
}
Deciding when to omit the braces is a matter of personal taste. Omitting them can make the code more brittle. If a second statement is later added to the "then" clause, a common mistake would be forgetting to add the newly required braces. The compiler cannot catch this sort of error; you'll just get the wrong results.
The if-then-else Statement
The if-then-else statement provides a secondary path of execution when an "if" clause evaluates to false. You could use an if-then-else statement in the applyBrakes method to take some action if the brakes are applied when the bicycle is not in motion. In this case, the action is to simply print an error message stating that the bicycle has already stopped.
void applyBrakes() {
if (isMoving) {
currentSpeed--;
} else {
System.err.println("The bicycle has already stopped!");
}
}
The following program, IfElseDemo, assigns a grade based on the value of a test score: an A for a score of 90% or above, a B for a score of 80% or above, and so on.
class IfElseDemo {
public static void main(String[] args) {
int testscore = 76;
char grade;
if (testscore >= 90) {
grade = 'A';
} else if (testscore >= 80) {
grade = 'B';
} else if (testscore >= 70) {
grade = 'C';
} else if (testscore >= 60) {
grade = 'D';
} else {
grade = 'F';
}
System.out.println("Grade = " + grade);
}
}
The output from the program is:
Grade = C
You may have noticed that the value of testscore can satisfy more than one expression in the compound statement: 76 >= 70 and 76 >= 60. However, once a condition is satisfied, the appropriate statements are executed (grade = 'C';) and the remaining conditions are not evaluated.
Control Flow Statements
The statements inside your source files are generally executed from top to bottom, in the order that they appear. Control flow statements, however, break up the flow of execution by employing decision making, looping, and branching, enabling your program to conditionally execute particular blocks of code. This section describes the decision-making statements (if-then, if-then-else, switch), the looping statements (for, while, do-while), and the branching statements (break, continue, return) supported by the Java programming language.
The switch Statement
Unlike if-then and if-then-else statements, the switch statement can have a number of possible execution paths. A switch works with the byte, short, char, and int primitive data types. It also works with enumerated types (discussed in Enum Types), the String class, and a few special classes that wrap certain primitive types: Character, Byte, Short, and Integer (discussed in Numbers and Strings).
The following code example, SwitchDemo, declares an int named month whose value represents a month. The code displays the name of the month, based on the value of month, using the switch statement.
public class SwitchDemo {
public static void main(String[] args) {
int month = 8;
String monthString;
switch (month) {
case 1: monthString = "January";
break;
case 2: monthString = "February";
break;
case 3: monthString = "March";
break;
case 4: monthString = "April";
break;
case 5: monthString = "May";
break;
case 6: monthString = "June";
break;
case 7: monthString = "July";
break;
case 8: monthString = "August";
break;
case 9: monthString = "September";
break;
case 10: monthString = "October";
break;
case 11: monthString = "November";
break;
case 12: monthString = "December";
break;
default: monthString = "Invalid month";
break;
}
System.out.println(monthString);
}
}
In this case, August is printed to standard output.
The body of a switch statement is known as a switch block. A statement in the switch block can be labeled with one or more case or default labels. The switch statement evaluates its expression, then executes all statements that follow the matching case label.
You could also display the name of the month with if-then-else statements:
int month = 8;
if (month == 1) {
System.out.println("January");
} else if (month == 2) {
System.out.println("February");
}
... // and so on
Deciding whether to use if-then-else statements or a switch statement is based on readability and the expression that the statement is testing. An if-then-else statement can test expressions based on ranges of values or conditions, whereas a switch statement tests expressions based only on a single integer, enumerated value, or String object.
Another point of interest is the break statement. Each break statement terminates the enclosing switch statement. Control flow continues with the first statement following the switch block. The break statements are necessary because without them, statements in switch blocks fall through: All statements after the matching case label are executed in sequence, regardless of the expression of subsequent case labels, until a break statement is encountered. The program SwitchDemoFallThrough shows statements in a switch block that fall through. The program displays the month corresponding to the integer month and the months that follow in the year:
public class SwitchDemoFallThrough {
public static void main(String[] args) {
java.util.ArrayList<String> futureMonths =
new java.util.ArrayList<String>();
int month = 8;
switch (month) {
case 1: futureMonths.add("January");
case 2: futureMonths.add("February");
case 3: futureMonths.add("March");
case 4: futureMonths.add("April");
case 5: futureMonths.add("May");
case 6: futureMonths.add("June");
case 7: futureMonths.add("July");
case 8: futureMonths.add("August");
case 9: futureMonths.add("September");
case 10: futureMonths.add("October");
case 11: futureMonths.add("November");
case 12: futureMonths.add("December");
break;
default: break;
}
if (futureMonths.isEmpty()) {
System.out.println("Invalid month number");
} else {
for (String monthName : futureMonths) {
System.out.println(monthName);
}
}
}
}
This is the output from the code:
August
September
October
November
December
Technically, the final break is not required because flow falls out of the switch statement. Using a break is recommended so that modifying the code is easier and less error prone. The default section handles all values that are not explicitly handled by one of the case sections.
The following code example, SwitchDemo2, shows how a statement can have multiple case labels. The code example calculates the number of days in a particular month:
class SwitchDemo2 {
public static void main(String[] args) {
int month = 2;
int year = 2000;
int numDays = 0;
switch (month) {
case 1: case 3: case 5:
case 7: case 8: case 10:
case 12:
numDays = 31;
break;
case 4: case 6:
case 9: case 11:
numDays = 30;
break;
case 2:
if (((year % 4 == 0) &&
!(year % 100 == 0))
|| (year % 400 == 0))
numDays = 29;
else
numDays = 28;
break;
default:
System.out.println("Invalid month.");
break;
}
System.out.println("Number of Days = "
+ numDays);
}
}
This is the output from the code:
Number of Days = 29
Using Strings in switch Statements
In Java SE 7 and later, you can use a String object in the switch statement's expression. The following code example, StringSwitchDemo, displays the number of the month based on the value of the String named month:
public class StringSwitchDemo {
public static int getMonthNumber(String month) {
int monthNumber = 0;
if (month == null) {
return monthNumber;
}
switch (month.toLowerCase()) {
case "january":
monthNumber = 1;
break;
case "february":
monthNumber = 2;
break;
case "march":
monthNumber = 3;
break;
case "april":
monthNumber = 4;
break;
case "may":
monthNumber = 5;
break;
case "june":
monthNumber = 6;
break;
case "july":
monthNumber = 7;
break;
case "august":
monthNumber = 8;
break;
case "september":
monthNumber = 9;
break;
case "october":
monthNumber = 10;
break;
case "november":
monthNumber = 11;
break;
case "december":
monthNumber = 12;
break;
default:
monthNumber = 0;
break;
}
return monthNumber;
}
public static void main(String[] args) {
String month = "August";
int returnedMonthNumber =
StringSwitchDemo.getMonthNumber(month);
if (returnedMonthNumber == 0) {
System.out.println("Invalid month");
} else {
System.out.println(returnedMonthNumber);
}
}
}
The output from this code is 8.
The String in the switch expression is compared with the expressions associated with each case label as if the String.equals method were being used. In order for the StringSwitchDemo example to accept any month regardless of case, month is converted to lowercase (with the toLowerCase method), and all the strings associated with the case labels are in lowercase.
Note: This example checks if the expression in the switch statement is null. Ensure that the expression in any switch statement is not null to prevent a NullPointerException from being thrown.
The while and do-while Statements
The while statement continually executes a block of statements while a particular condition is true. Its syntax can be expressed as:
while (expression) {
statement(s)
}
The while statement evaluates expression, which must return a boolean value. If the expression evaluates to true, the while statement executes the statement(s) in the while block. The while statement continues testing the expression and executing its block until the expression evaluates to false. Using the while statement to print the values from 1 through 10 can be accomplished as in the following WhileDemo program:
class WhileDemo {
public static void main(String[] args){
int count = 1;
while (count < 11) {
System.out.println("Count is: " + count);
count++;
}
}
}
You can implement an infinite loop using the while statement as follows:
while (true){
// your code goes here
}
The Java programming language also provides a do-while statement, which can be expressed as follows:
do {
statement(s)
} while (expression);
The difference between do-while and while is that do-while evaluates its expression at the bottom of the loop instead of the top. Therefore, the statements within the do block are always executed at least once, as shown in the following DoWhileDemo program:
class DoWhileDemo {
public static void main(String[] args){
int count = 1;
do {
System.out.println("Count is: " + count);
count++;
} while (count < 11);
}
}
The for Statement
The for statement provides a compact way to iterate over a range of values. Programmers often refer to it as the "for loop" because of the way in which it repeatedly loops until a particular condition is satisfied. The general form of the for statement can be expressed as follows:
for (initialization; termination;
increment) {
statement(s)
}
When using this version of the for statement, keep in mind that:
• The initialization expression initializes the loop; it's executed once, as the loop begins.
• When the termination expression evaluates to false, the loop terminates.
• The increment expression is invoked after each iteration through the loop; it is perfectly acceptable for this expression to increment or decrement a value.
The following program, ForDemo, uses the general form of the for statement to print the numbers 1 through 10 to standard output:
class ForDemo {
public static void main(String[] args){
for(int i=1; i<11; i++){
System.out.println("Count is: " + i);
}
}
}
The output of this program is:
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
Count is: 6
Count is: 7
Count is: 8
Count is: 9
Count is: 10
Notice how the code declares a variable within the initialization expression. The scope of this variable extends from its declaration to the end of the block governed by the for statement, so it can be used in the termination and increment expressions as well. If the variable that controls a for statement is not needed outside of the loop, it's best to declare the variable in the initialization expression. The names i, j, and k are often used to control for loops; declaring them within the initialization expression limits their life span and reduces errors.
The three expressions of the for loop are optional; an infinite loop can be created as follows:
// infinite loop
for ( ; ; ) {
// your code goes here
}
The for statement also has another form designed for iteration through Collections and arrays This form is sometimes referred to as the enhanced for statement, and can be used to make your loops more compact and easy to read. To demonstrate, consider the following array, which holds the numbers 1 through 10:
int[] numbers = {1,2,3,4,5,6,7,8,9,10};
The following program, EnhancedForDemo, uses the enhanced for to loop through the array:
class EnhancedForDemo {
public static void main(String[] args){
int[] numbers =
{1,2,3,4,5,6,7,8,9,10};
for (int item : numbers) {
System.out.println("Count is: " + item);
}
}
}
In this example, the variable item holds the current value from the numbers array. The output from this program is the same as before:
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
Count is: 6
Count is: 7
Count is: 8
Count is: 9
Count is: 10
We recommend using this form of the for statement instead of the general form whenever possible.
Branching Statements
The break Statement
The break statement has two forms: labeled and unlabeled. You saw the unlabeled form in the previous discussion of the switch statement. You can also use an unlabeled break to terminate a for, while, or do-while loop, as shown in the following BreakDemo program:
class BreakDemo {
public static void main(String[] args) {
int[] arrayOfInts =
{ 32, 87, 3, 589,
12, 1076, 2000,
8, 622, 127 };
int searchfor = 12;
int i;
boolean foundIt = false;
for (i = 0; i < arrayOfInts.length; i++) {
if (arrayOfInts[i] == searchfor) {
foundIt = true;
break;
}
}
if (foundIt) {
System.out.println("Found " + searchfor + " at index " + i);
} else {
System.out.println(searchfor + " not in the array");
}
}
}
This program searches for the number 12 in an array. The break statement, shown in boldface, terminates the for loop when that value is found. Control flow then transfers to the statement after the for loop. This program's output is:
Found 12 at index 4
An unlabeled break statement terminates the innermost switch, for, while, or do-while statement, but a labeled break terminates an outer statement. The following program, BreakWithLabelDemo, is similar to the previous program, but uses nested for loops to search for a value in a two-dimensional array. When the value is found, a labeled break terminates the outer for loop (labeled "search"):
class BreakWithLabelDemo {
public static void main(String[] args) {
int[][] arrayOfInts = {
{ 32, 87, 3, 589 },
{ 12, 1076, 2000, 8 },
{ 622, 127, 77, 955 }
};
int searchfor = 12;
int i;
int j = 0;
boolean foundIt = false;
search:
for (i = 0; i < arrayOfInts.length; i++) {
for (j = 0; j < arrayOfInts[i].length;
j++) {
if (arrayOfInts[i][j] == searchfor) {
foundIt = true;
break search;
}
}
}
if (foundIt) {
System.out.println("Found " + searchfor + " at " + i + ", " + j);
} else {
System.out.println(searchfor + " not in the array");
}
}
}
This is the output of the program.
Found 12 at 1, 0
The break statement terminates the labeled statement; it does not transfer the flow of control to the label. Control flow is transferred to the statement immediately following the labeled (terminated) statement.
The continue Statement
The continue statement skips the current iteration of a for, while , or do-while loop. The unlabeled form skips to the end of the innermost loop's body and evaluates the boolean expression that controls the loop. The following program, ContinueDemo , steps through a String, counting the occurences of the letter "p". If the current character is not a p, the continue statement skips the rest of the loop and proceeds to the next character. If it is a "p", the program increments the letter count.
class ContinueDemo {
public static void main(String[] args) {
String searchMe = "peter piper picked a " + "peck of pickled peppers";
int max = searchMe.length();
int numPs = 0;
for (int i = 0; i < max; i++) {
// interested only in p's
if (searchMe.charAt(i) != 'p')
continue;
// process p's
numPs++;
}
System.out.println("Found " + numPs + " p's in the string.");
}
}
Here is the output of this program:
Found 9 p's in the string.
To see this effect more clearly, try removing the continue statement and recompiling. When you run the program again, the count will be wrong, saying that it found 35 p's instead of 9.
A labeled continue statement skips the current iteration of an outer loop marked with the given label. The following example program, ContinueWithLabelDemo, uses nested loops to search for a substring within another string. Two nested loops are required: one to iterate over the substring and one to iterate over the string being searched. The following program, ContinueWithLabelDemo, uses the labeled form of continue to skip an iteration in the outer loop.
class ContinueWithLabelDemo {
public static void main(String[] args) {
String searchMe = "Look for a substring in me";
String substring = "sub";
boolean foundIt = false;
int max = searchMe.length() -
substring.length();
test:
for (int i = 0; i <= max; i++) {
int n = substring.length();
int j = i;
int k = 0;
while (n-- != 0) {
if (searchMe.charAt(j++) != substring.charAt(k++)) {
continue test;
}
}
foundIt = true;
break test;
}
System.out.println(foundIt ? "Found it" : "Didn't find it");
}
}
Here is the output from this program.
Found it
The return Statement
The last of the branching statements is the return statement. The return statement exits from the current method, and control flow returns to where the method was invoked. The return statement has two forms: one that returns a value, and one that doesn't. To return a value, simply put the value (or an expression that calculates the value) after the return keyword.
return ++count;
The data type of the returned value must match the type of the method's declared return value. When a method is declared void, use the form of return that doesn't return a value.
return;
The Classes and Objects lesson will cover everything you need to know about writing methods.
Summary of Control Flow Statements
The if-then statement is the most basic of all the control flow statements. It tells your program to execute a certain section of code only if a particular test evaluates to true. The if-then-else statement provides a secondary path of execution when an "if" clause evaluates to false. Unlike if-then and if-then-else, the switch statement allows for any number of possible execution paths. The while and do-while statements continually execute a block of statements while a particular condition is true. The difference between do-while and while is that do-while evaluates its expression at the bottom of the loop instead of the top. Therefore, the statements within the do block are always executed at least once. The for statement provides a compact way to iterate over a range of values. It has two forms, one of which was designed for looping through collections and arrays
Questions and Exercises: Control Flow Statements
Questions
1. The most basic control flow statement supported by the Java programming language is the ___ statement.
2. The ___ statement allows for any number of possible execution paths.
3. The ___ statement is similar to the while statement, but evaluates its expression at the ___ of the loop.
4. How do you write an infinite loop using the for statement?
5. How do you write an infinite loop using the while statement?
Exercises
1. Consider the following code snippet.
2. if (aNumber >= 0)
3. if (aNumber == 0)
4. System.out.println("first string");
5. else System.out.println("second string");
6. System.out.println("third string");
a. What output do you think the code will produce if aNumber is 3?
b. Write a test program containing the previous code snippet; make aNumber 3. What is the output of the program? Is it what you predicted? Explain why the output is what it is; in other words, what is the control flow for the code snippet?
c. Using only spaces and line breaks, reformat the code snippet to make the control flow easier to understand.
d. Use braces, { and }, to further clarify the code
Answers to Questions and Exercises: Control Flow Statements
Answers to Questions
1. The most basic control flow statement supported by the Java programming language is the if-then statement.
2. The switch statement allows for any number of possible execution paths.
3. The do-while statement is similar to the while statement, but evaluates its expression at the bottom of the loop.
4. Question: How do you write an infinite loop using the for statement?
Answer:
for ( ; ; ) {
}
5. Question: How do you write an infinite loop using the while statement?
Answer:
while (true) {
}
Exercises
1. Consider the following code snippet.
2. if (aNumber >= 0)
3. if (aNumber == 0)
4. System.out.println("first string");
5. else
6. System.out.println("second string");
7. System.out.println("third string");
a. Exercise: What output do you think the code will produce if aNumber is 3?
Solution:
second string
third string
b. Exercise: Write a test program containing the previous code snippet; make aNumber 3. What is the output of the program? Is it what you predicted? Explain why the output is what it is. In other words, what is the control flow for the code snippet?
Solution: NestedIf
second string
third string
3 is greater than or equal to 0, so execution progresses to the second if statement. The second if statement's test fails because 3 is not equal to 0. Thus, the else clause executes (since it's attached to the second if statement). Thus, second string is displayed. The final println is completely outside of any if statement, so it always gets executed, and thus third string is always displayed.
c. Exercise: Using only spaces and line breaks, reformat the code snippet to make the control flow easier to understand.
Solution:
if (aNumber >= 0)
if (aNumber == 0)
System.out.println("first string");
else
System.out.println("second string");
System.out.println("third string");
d. Exercise: Use braces { and } to further clarify the code and reduce the possibility of errors by future maintainers of the code.
Solution:
if (aNumber >= 0) {
if (aNumber == 0) {
System.out.println("first string");
} else {
System.out.println("second string");
}
}
System.out.println("third string");
Pertemuan 6 sd. 11 (12 JP)
3.2. Memahami struktur algoritma serta menganalisis data dalam suatu algoritma percabangan.
4.2. Menggunakan algoritma percabangan untuk memecahkan permasalahan.
Pertemuan 12 sd. 17 (10 JP)
3.3. Memahami struktur algoritma serta menganalisa data dalam suatu algoritma perulangan.
4.3. Memecahkan permasalahan dengan algoritma perulangan.
3.1. Memahami penggunaan data dalam algoritma dan konsep algoritma pemrograman.
4.1. Menggunakan algoritma pemrograman untuk memecahkan permasalahan.
1. Persiapan Instalasi JDK
- Download Java Development Kit (JDK), buka web browser misal Mozilla Firefox, di address bar ketik : java.sun.com
- Pada pilihan Downloads, pilih Java SE, dan pilih JDK yang teruptodate. Dan Install file JDK yang sudah berhasil di download.
- Kemudian masuk ke CMD, waktu di c:\> kita ketik javac maka seakan javac belum terinstall. Aturlah path system Windows. Bukalah folder javac terinstall yaitu di C:\Program Files\Java\JDK 7.0.1\bin, klik kanan file javac lalu pilih properties, copy File Location.
- Klik Start, klik kanan My Computer, pilih Properties, pilih Advanced system setting, environment variables.
- Pada New User Variable pilih New, ketik pada Variable name : Path, dan pada Variable value, pastekan alamat yang sudah dicopy tadi. Dan klik OK pada setiap kotak dialog. Sekarang coba lagi di CMD, panggil javac sekali lagi.
2. Menjalankan Java dengan Editor NotePad++
- Buka Notepad++, File – New, File – Save As, buat folder khusus untuk latihan misal di D:\ bernama Test, dan beri nama youtube.java
- Ketik pertama kali sebuah class misal bernama apples, caranya
class Apples {
}
- Buatlah method, yaitu public static void main (String args []){ } sehingga seperti berikut…
class Apples {
public static void main (String args []){
}
}
- Selanjutnya buat instruksi statemen misalnya menampilkan kata Hello youtube! Sbb...
class Apples {
public static void main (String args []){
System.out.println(“Hello youtube!”);
}
}
- Simpan file lalu pergi ke CMD lagi, pindah ke tempat penyimpanan file di folder Test.
D:
Cd \
dir
Cd test
Dir
- Ada file youtube.java lalu kita compile agar menjadi class
javac youtube.java
dir
- Ada file apples.class lalu kita panggil file tersebut.
java youtube
- akan muncul teks : Hello youtube!
- Pada address bar web browser ketik eclipse.org, pilih downloads, Eclipse IDE for Java EE Developers (163 MB) for Windows.
- Extract file yang dicopy, dan pada file eclipse.exe, klik kanan lalu send to desktop. Jalankan melalui desktop.
- File – New Project, pada Project name : ketik nama proyek misal LATJAVA, maka muncul nama folder LATJAVA. Buka panah kiri folder, ada 2 folder lagi yaitu src (source) dan JRE SystemLibrary.
- Pada src, klik kanan, pilih New – Class. Pada Name: ketik yang tadi, apples, dan Finish. Copy paste isi file di NotePad++ tadi ke dalam editor eclipse. Dan simpan.
- Untuk menjalankan file ini pilih Run, bisa melalui shortcut panah hijau, atau menu. Pada kotak dialog Save and Launch pilih java Application. OK. Dibar bawah ada muncul hasilnya.
- Jika script salah dan tetap dijalankan maka akan ada banyak informasi kesalahan, baik di layar editor maupun di bar tempat tampilan.
4. Hello youtube!
- Di eclipse dapat ditampilkan line number, melalui Window, Preferences, General, Editors, Text Editor, show line numbers. Apply, OK.
- Di java semua dimulai dengan class, didalamnya ada dua kurung kurawal buka dan tutup. , contohnya seperti berikut.
class apples{
}
c. Di dalam class ada method, contoh method bernama bakecake, dimana didalamnya ada instruksi instruksi, misalnya…
class apples{
void bakecake(){
mix batter;
put in oven;
eat the fine cake;
}
}
d. Main method adalah paling dasar dalam java, contohnya..
class apples{
public static void main(String args[]){
System.out.println(“Hello youtube”);
}
}
e. Penjelasan dari program dasar java ini adalah…
nama class : class apples{}
method header : public static void main(String args[]){}
method body : System.out.println(“Hello youtube”);
5. Variable
Double tuna;
Tuna = 5.28;
System.out.print(tuna);
Lihat hasilnya… ketik lagi yang berikut.
Double tuna;
Tuna = 5.28;
System.out.print(“I want “);
System.out.print(tuna);
System.out.println(“ movies”); lihat hasilnya lalu ketik lagi…
System.out.print(“movies“);
6. Getting User Input, mengambil data dari keyboard, kita impor utility Scanner.
import java.util.Scanner;
class apples{
public static void main(String args[]){
Scanner namaku = new Scanner(System.in);
System.out.println(namaku.nextLine());
//untuk data string .nextLine
}
}
7. Kalkulator sederhana
Import java.util.Scanner;
class apples{
public static void main(String args[]){
Scanner jono = new Scanner(System.in);
double angka1, angka2, tambah;
System.out.println(“Masukkan angka pertama : “);
angka1 = jono.nextDouble();
// nextDouble untuk data jenis angka (value)
System.out.println(“Masukkan angka kedua : “);
angka2 = jono.nextDouble();
tambah = angka1 + angka2;
System.out.println(“Jika dijumlahkan : “+tambah);
}
}
8. Operator matematik, ada beberapa operator matematik seperti +, -, *, /, % yang dapat digunakan. Contoh berikut :
import java.util.Scanner;
class apples{
public static void main (Stiring args[]){
Scanner masuk = new Scanner(System.in);
int angka1, angka2, hasil;
angka1 = 11;
angka2 = 3;
hasil = angka1 + angka2;
System.out.println(hasil);
hasil=angka1 / angka2;
}
}
Pertemuan 2
9. Mendapatkan Input dari Keyboard menggunakan BufferedReader.
Jika sebelumnya kita mendapatkan input dari keyboard menggunakan import.util.Scanner, sekarang menggunakan input.java.io.*
Disamping itu menambahkan statement :
BufferedReader dataIn = new BufferedReader(new InputStreamReader( System.in) );
Dan variabel String temporary untuk input, fungsi readLine(), dan blok try-catch seperti berikut:
try{
String temp = dataIn.readLine();
}
catch( IOException e ){
System.out.println(“Error in getting input”);
}
Berikut contoh lengkap source codenya, simpan dengan nama file DataDariKeyboard.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class DataDariKeyboard {
public static void main( String[] args ){
BufferedReader dataIn = new BufferedReader(new
InputStreamReader(System.in) );
String nama = "";
System.out.print("Silahkan Masukkan Nama Anda:");
try{
nama = dataIn.readLine();
}catch( IOException e ){
System.out.println("Salah!");
}
System.out.println("Assalamualaikum " + nama +"!");
}
}
10. Menggunakan JOptionPane.
Cara lain adalah menggunakan class JOptionPane dari package javax.swing dan memunculkan dialog box standart yang lebih menarik bagi user. Contoh buat class bernama DataDariJOption
import javax.swing.JOptionPane;
public class DataDariJOption{
public static void main( String[] args ){
String nama = "";
nama = JOptionPane.showInputDialog("Masukkan Nama Anda : ");
String pesan = "Assalamualaikum " + nama + "!";
JOptionPane.showMessageDialog(null, pesan);
}
}
LATIHAN
1. Buatlah 3 input kata menggunakan BufferedReader dan tampilkan ke3 kata tersebut menjadi sebuah kalimat. Contoh tampilan program :
Masukkan kata pertama : Kami
Masukkan kata kedua : Belajar
Masukkan kata ketiga : Java
Kami Belajar Java
2. Buatlah hal yang sama menggunakan JOptionPane untuk 3 input kata, dan tampilan ke 3 kata tersebut menjadi sebuah kalimat seperti tampilan di atas.
Pertemuan 3
11. Tipe Dasar Variabel Data.
a. Data primitive
(1) byte : data 8-bit. minimum -128 atau (-2^7), maksimum 127 atau (2^7)-1
Contoh : byte a = 100;
byte b = -58;
(2) short : data 16-bit, minimum -32.768 atau (-2^16), maksimum 32.767 atau (2^16)-1
Contoh : short c = 10000;
short d = -20000;
(3) int: data 32-bit. minimum - 2,147,483,648 atau.(-2^31), maksimum 2,147,483,647 atau.(2^31 -1)
Contoh : int e = 100000;
int f = -200000;
(4) long: data 64-bit. minimum -9,223,372,036,854,775,808 atau (-2^63), maksimum 9,223,372,036,854,775,807 atau (2^63 -1)
Contoh : long g = 100000L;
long h = -200000L;
(5) float: data 32-bit dengan presisi single floating point, sehingga tidak pernah untuk hitungan presisi seperti keuangan.
Contoh : float i = 234.5f;
(6) double: data 64-bit dengan presisi double floating point, juga tidak pernah untuk hitungan presisi seperti keuangan.
Contoh : double j = 234.56d;
(7) boolean: data 1-bit informasi dengan dua kemungkinan yaitu true dan false.
Contoh : boolean lulus = false;
(8) char: data 16-bit UNICODE character. Minimum '\u0000' atau 0 dan maksimum '\uffff' atau 65,535.
Contoh : char A = ‘A’;
b. Data reference, dibuat menggunakan konstruktor class
Contoh : Binatang binatang = new Binatang(“Singa”);
12. Tipe Variabel Data.
a. Variabel local.
Dideklarasikan dalam method, constructor dan block. Contoh :
public class Test{
public void pupUsia(){
int usia = 0;
usia = usia + 7;
System.out.println("Umur Jono adalah : " + usia);
}
public static void main(String args[]){
Test test = new Test();
test.pupUsia();
}
}
b. Variabel Instance.
Dideklarasikan dalam class, diluar method, constructor atau block. Contoh :
import java.io.*;
public class Karyawan{
// variabel istance ini nampak untuk class turunannya.
public String nama;
// variabel gaji nampak hanya dalam class Karyawan.
private double gaji;
// Variabel Nama ditugaskan di constructor.
public Karyawan (String karNama){
nama = karNama;
}
// Variabel gaji bertype nilai.
public void setGaji(double karGaji){
gaji = karGaji;
}
// Method ini akan mencetak rincian karyawan.
public void cetakKar(){
System.out.println("Nama : " + nama );
System.out.println("Gaji :" + gaji);
}
public static void main(String args[]){
Employee karSatu = new Karyawan("Ransika");
karSatu.setGaji(1000);
karSatu.cetakKar();
}
}
c. Variabel Class/Static.
Dideklarasikan dalam class, diluar method, constructor atau block. Contoh :
import java.io.*;
public class Karyawan2{
// variable gaji adalah sebuah variabel private static
private static double gaji;
// DEPARTMENT adalah konstanta
public static final String DEPARTMENT = "Development ";
public static void main(String args[]){
gaji = 1000;
System.out.println(DEPARTMENT+"average salary:"+gaji);
}
}
TUGAS: X MM 1, SELASA 11-NOP-2014, JAM 7-8
X MM 2, RABU 12-NOP-2014, JAM 1-2
Java Applet adalah aplikasi java yang bisa disisipkan kedalam halaman HTML. Java applet bisa berjalan pada web browser yang telah mendukung java seperti mozilla, IE, dan chrome. Applet dirancang untuk berjalan ‘remotely‘ pada browser client, sehingga ada beberapa keterbatasan. Secara default, applet tidak bisa mengakses resource pada komputer lokal. Applet biasanya digunakan untuk membuat website lebih dinamis dan menghibur.
1. Contoh membuat Applet dengan tampilan “Assalamu’alaikum”
import java.awt.*;
import java.applet.*;
/* <applet code = "CobaAppletSalam" width = 300 height = 300> </applet> */
public class CobaAppletSalam extends Applet {
public void paint (Graphics g) {
g.drawString("Hello world!", 80, 25);
}
}
2. Simpan dengan nama CobaAppletSalam.java. Dan untuk menjalankan di prompt, dengan perintah berikut :
D:\>appletviewer CobaAppletSalam.java
Untuk kembali ke CMD tutup terlebih dahulu appletviewer.
3. Latihan membuat gambar Lampu seperti berikut.
import java.awt.*;
import java.applet.*;
/* <applet code="Lamp" width =600 height = 800></applet> */
public class Lamp extends Applet {
public void paint(Graphics g) {
// template untuk membuat applet
g.fillRect(50,250,290,290);
// dasar lampu berupa segiempat
g.drawLine(125,250,125,160);
g.drawLine(175,250,175,160);
// garis tegak dua buah
g.drawArc(85,157,130,50,-65,312);
g.drawArc(85,87,130,50,62,58);
// sudut lingkaran
g.drawLine(85,177,119,89);
g.drawLine(215,177,181,89);
// garis penghubung sudut lingkaran
g.fillArc(78,120,40,40,63,-174);
g.fillOval(120,96,40,40);
g.fillArc(173,100,40,40,110,180);
// memberi variasi dalam kap lampu
}
}
Soal Ulangan Harian
1. Symbol flowchart yang digunakan untuk menyatakan mulai atau selesai disebut
A. Terminator C. Input/Output
B. Process D. Selection/Decision
E. Pre-defined Data
2. Macam – macam dari tipe data dasar adalah sebagai berikut, kecuali
A. Integer C. Char
B. Real D. Boolean E. Array
3. Tipe data untuk menyatakan karakter data tunggal adalah
A. Integer C. Char
B. Real D. Boolean E. Array
4. Berikut ini merupakan keyword (kata kunci) pada java, kecuali
A. Import C. super
B. unit D. extends E. new
5. Nama yang diciptakan oleh pemrogram digunakan untuk memberi nama kelas atau variable pada java disebut
A. keyword C. identifier
B. character D. literal E. variable
6. Aplikasi java yang dapat disisipkan ke halaman html adalah…
A. applet C. bufferedReader
B. swing D. streamReader E. lang
STRUKTUR KONTROL
1. if – else
2. if – ilse if
3. if – else if – else
4. switch – case – break – default
import java.util.Scanner;
public class Uji_switchcase{
public static void main (String args[]){
System.out.print("Masukkan Nilai anda : ");
Scanner gayung = new Scanner(System.in);
int Nilai ;
Nilai = gayung.nextInt();
switch (Nilai) {
case 4:
System.out.println("Keterangan : Sangat Baik");
break;
case 3:
System.out.println("Keterangan : Baik");
break;
case 2:
System.out.println("Keterangan : Cukup");
break;
case 1:
System.out.println("Keterangan : Kurang");
break;
default:
System.out.println("Maaf, nilai anda salah!!");
} } }
TUGAS :
BUATLAH PROGRAM UNTUK MENAMPILKAN NAMA BULAN (JANUARI, FEBRUARI DST) JIKA ANDA MEMASUKKAN ANGKA 1 SD 12. SELAIN ANGKA ITU BERI PESAN KESALAHAN…
Nama class : Uji_bulan.java
5. while – loop (untuk perulangan)
contoh : menampilkan angka 1 sd 10
hasil : 1 2 3 4 5 6 7 8 9 10
1
2
3
4
public class Uji_loop1{
public static void main (String [] args){
int angka = 1;
while (angka<=10){
System.out.print(angka+", ");
angka=angka+1;
}
}
}
TUGAS 1:
BUATLAH DERET ANGKA 2, 4, 6, 8, 10, 12,
Nama Class : Uji_loop2.java
Tugas 2 :
Buatlah deret angka : 200, 175, 150, 125, 100, 75, 50, 25, 0
Nama class : Uji_loop3.java
Tugas Kompleks :
public class Ayam{
public static void main (String args []){
int mati;
int ayam=100;
String teks ="tek kotek kotek kotek... anak ayam turun ";
for (mati = 1; mati <=100; mati++){
if (ayam<=1){
System.out.println(teks+ayam+" mati 1 tinggal induknya ");
break;
}
System.out.println(teks+ayam+" mati 1 tinggal "+(ayam-1));
ayam--;
}
}}
Pertemuan ke
Materi :
Pernyataan Break
1. Break tidak berlabel
a. Untuk menghentikan perintah switch
b. Untuk menghentikan for, while, dan do-while
Contoh :
String nama[] = {“Yono”, “Yayuk”, “Yahya”, “Iin”, “Wisnu”, “Susi”}
String cariNama = “Wisnu”;
boolean ketemuNama=false;
for (int i=0, i<nama.lengh; i++0{
if(nama[i].equals(cariNama)){
ketemuNama=true;
break;
}}
If (ketemuNama){
System.out.println(cariNama+ “ ditemukan!”);
}
else{
System.out.println(cariNama+ “ tidak ditemukan!”);
}
Buat nama class Break_komp1mm2.java,Break_laptop1mm2
Dalam program ada nama panggilan yang membuat
2. Break berlabel
a. Menghentikan pernyataan yang diberi label
Pernyataan Continue
1. Continue tidak berlabel
a.
Pernyataan Percabangan
1. Pernyataan Break
Pernyataan break memiliki dua bentuk: tidak berlabel (unlabeled) dan berlabel (labeled).
• Pernyataan Break Tidak Berlabel
Definisi :
Pernyataan break tidak berlabel (unlabeled) digunakan untuk menghentikan jalannya pernyataan switch. Selain itu pernyataan break unlabeled juga bisa digunakan untuk menghentikan pernyataan-pernyataan for, while atau do-while loop.
Contoh Program :
public class BelajarJava {
public static void main(String[] args) {
String names[] = {"Mojo", "Tika"};
String searchName = "Mojo";
boolean foundName = false;
for( int i=0; i< names.length; i++ ){
if( names[i].equals( searchName )){
foundName = true;
break;
}
}
if( foundName ){
System.out.println( searchName + " found!" );
}
else{
}
}
}
• Pernyataan Break Berlabel
Definisi:
Bentuk label dari pernyataan break akan menghentikan pernyataan di luarnya, dimana sebelumnya harus diberikan label yang sudah di spesifikasikan pada program pada pernyataan break. Program berikut ini akan mencari nilai dalam array dua dimensi.
Terdapat dua pengulangan bersarang (nested loop). Ketika sebuah nilai ditemukan break akan menghentikan pernyataan yang diberi label searchLabel yang terletak di luar pernyataan for loop.
Contoh program :
public class BelajarJava {
public static void main(String[] args) {
int[][] numbers = {{1, 2, 3},
{4, 5, 6},
{7, 8, 9}};
int searchNum = 5;
boolean foundNum = false;
searchLabel:
for( int i=0; ifor( int j=0; jif( searchNum == numbers[i][j] ){
foundNum = true;
break searchLabel;
}
}
}
if( foundNum ){
System.out.println( searchNum + " found!" );
}
else{
}
}
}
2. Pernyataan Continue
Pernyataan continue memiliki dua bentuk: berlabel dan tidak berlabel. Anda dapat
menggunakan pernyataan continue untuk melanjutkan pengulangan yang sedang
dijalankan oleh pernyataan for, while, atau do- while loop.
• Pernyataan Continue Tidak Berlabel
Definisi :
Bentuk pernyataan continue tidak berlabel (unlabeled) akan melewati bagian pernyataan setelah pernyataan ini dituliskan dan memeriksa eksepresi logika (boolean) yang mengkontrol pengulangan. Jika ekspresi logika (boolean) masih bernilai true, maka pengulangan tetap dilanjutkan. Pada dasarnya pernyataan ini akan melanjutkan bagian pengulangan pada pernyataan loop.
Contoh Program :
public class BelajarJava {
public static void main(String[] args) {
String names[] = {"Mojo", "Tika"};
int count = 0;
for( int i=0; iif( !names[i].equals("Mojo") ){
continue; //skip next statement
}
count++;
}
System.out.println("There are " + count + " Mojo in the list");
}
}
• Pernyataan Continue Berlabel
Definisi :
Bentuk pernyataan continue berlabel (labeled) akan melanjutkan pengulangan yang sedang terjadi dan dilanjuti ke pengulangan berikutnya dari pernyataan pengulangan yang diberi label (tanda).
Contoh Program :
public class BelajarJava {
public static void main(String[] args) {
outerLoop:
for( int i=0; i<5 br="" i="">for( int j=0; j<5 br="" j="">System.out.println("Inside for(j) loop"); //message1
if( j == 2 ) continue outerLoop;
}
System.out.println("Inside for(i) loop"); //message2
}
}
}
3. Return
Definisi :
Pernyataan return digunakan untuk keluar dari sebuah method. Pernyataan return memiliki dua bentuk: memberikan sebuah nilai, dan tidak memberikan nilai.
Untuk memberikan sebuah nilai, cukup berikan nilai (atau ekspresi yang menghasilkan sebuah nilai) sesudah kata return. Contohnya,
return ++count;
atau
return "Hello";
Tipe data dari nilai yang diberikan harus sama dengan tipe dari method yang dibuat. Ketika sebuah method void dideklariskan, gunakan bentuk return yang tidak memberikan nilai.
Contohnya,
return;
The if-then and if-then-else Statements
The if-then Statement
The if-then statement is the most basic of all the control flow statements. It tells your program to execute a certain section of code only if a particular test evaluates to true. For example, the Bicycle class could allow the brakes to decrease the bicycle's speed only if the bicycle is already in motion. One possible implementation of the applyBrakes method could be as follows:
void applyBrakes() {
// the "if" clause: bicycle must be moving
if (isMoving){
// the "then" clause: decrease current speed
currentSpeed--;
}
}
If this test evaluates to false (meaning that the bicycle is not in motion), control jumps to the end of the if-then statement.
In addition, the opening and closing braces are optional, provided that the "then" clause contains only one statement:
void applyBrakes() {
// same as above, but without braces
if (isMoving)
currentSpeed--;
}
Deciding when to omit the braces is a matter of personal taste. Omitting them can make the code more brittle. If a second statement is later added to the "then" clause, a common mistake would be forgetting to add the newly required braces. The compiler cannot catch this sort of error; you'll just get the wrong results.
The if-then-else Statement
The if-then-else statement provides a secondary path of execution when an "if" clause evaluates to false. You could use an if-then-else statement in the applyBrakes method to take some action if the brakes are applied when the bicycle is not in motion. In this case, the action is to simply print an error message stating that the bicycle has already stopped.
void applyBrakes() {
if (isMoving) {
currentSpeed--;
} else {
System.err.println("The bicycle has already stopped!");
}
}
The following program, IfElseDemo, assigns a grade based on the value of a test score: an A for a score of 90% or above, a B for a score of 80% or above, and so on.
class IfElseDemo {
public static void main(String[] args) {
int testscore = 76;
char grade;
if (testscore >= 90) {
grade = 'A';
} else if (testscore >= 80) {
grade = 'B';
} else if (testscore >= 70) {
grade = 'C';
} else if (testscore >= 60) {
grade = 'D';
} else {
grade = 'F';
}
System.out.println("Grade = " + grade);
}
}
The output from the program is:
Grade = C
You may have noticed that the value of testscore can satisfy more than one expression in the compound statement: 76 >= 70 and 76 >= 60. However, once a condition is satisfied, the appropriate statements are executed (grade = 'C';) and the remaining conditions are not evaluated.
Control Flow Statements
The statements inside your source files are generally executed from top to bottom, in the order that they appear. Control flow statements, however, break up the flow of execution by employing decision making, looping, and branching, enabling your program to conditionally execute particular blocks of code. This section describes the decision-making statements (if-then, if-then-else, switch), the looping statements (for, while, do-while), and the branching statements (break, continue, return) supported by the Java programming language.
The switch Statement
Unlike if-then and if-then-else statements, the switch statement can have a number of possible execution paths. A switch works with the byte, short, char, and int primitive data types. It also works with enumerated types (discussed in Enum Types), the String class, and a few special classes that wrap certain primitive types: Character, Byte, Short, and Integer (discussed in Numbers and Strings).
The following code example, SwitchDemo, declares an int named month whose value represents a month. The code displays the name of the month, based on the value of month, using the switch statement.
public class SwitchDemo {
public static void main(String[] args) {
int month = 8;
String monthString;
switch (month) {
case 1: monthString = "January";
break;
case 2: monthString = "February";
break;
case 3: monthString = "March";
break;
case 4: monthString = "April";
break;
case 5: monthString = "May";
break;
case 6: monthString = "June";
break;
case 7: monthString = "July";
break;
case 8: monthString = "August";
break;
case 9: monthString = "September";
break;
case 10: monthString = "October";
break;
case 11: monthString = "November";
break;
case 12: monthString = "December";
break;
default: monthString = "Invalid month";
break;
}
System.out.println(monthString);
}
}
In this case, August is printed to standard output.
The body of a switch statement is known as a switch block. A statement in the switch block can be labeled with one or more case or default labels. The switch statement evaluates its expression, then executes all statements that follow the matching case label.
You could also display the name of the month with if-then-else statements:
int month = 8;
if (month == 1) {
System.out.println("January");
} else if (month == 2) {
System.out.println("February");
}
... // and so on
Deciding whether to use if-then-else statements or a switch statement is based on readability and the expression that the statement is testing. An if-then-else statement can test expressions based on ranges of values or conditions, whereas a switch statement tests expressions based only on a single integer, enumerated value, or String object.
Another point of interest is the break statement. Each break statement terminates the enclosing switch statement. Control flow continues with the first statement following the switch block. The break statements are necessary because without them, statements in switch blocks fall through: All statements after the matching case label are executed in sequence, regardless of the expression of subsequent case labels, until a break statement is encountered. The program SwitchDemoFallThrough shows statements in a switch block that fall through. The program displays the month corresponding to the integer month and the months that follow in the year:
public class SwitchDemoFallThrough {
public static void main(String[] args) {
java.util.ArrayList<String> futureMonths =
new java.util.ArrayList<String>();
int month = 8;
switch (month) {
case 1: futureMonths.add("January");
case 2: futureMonths.add("February");
case 3: futureMonths.add("March");
case 4: futureMonths.add("April");
case 5: futureMonths.add("May");
case 6: futureMonths.add("June");
case 7: futureMonths.add("July");
case 8: futureMonths.add("August");
case 9: futureMonths.add("September");
case 10: futureMonths.add("October");
case 11: futureMonths.add("November");
case 12: futureMonths.add("December");
break;
default: break;
}
if (futureMonths.isEmpty()) {
System.out.println("Invalid month number");
} else {
for (String monthName : futureMonths) {
System.out.println(monthName);
}
}
}
}
This is the output from the code:
August
September
October
November
December
Technically, the final break is not required because flow falls out of the switch statement. Using a break is recommended so that modifying the code is easier and less error prone. The default section handles all values that are not explicitly handled by one of the case sections.
The following code example, SwitchDemo2, shows how a statement can have multiple case labels. The code example calculates the number of days in a particular month:
class SwitchDemo2 {
public static void main(String[] args) {
int month = 2;
int year = 2000;
int numDays = 0;
switch (month) {
case 1: case 3: case 5:
case 7: case 8: case 10:
case 12:
numDays = 31;
break;
case 4: case 6:
case 9: case 11:
numDays = 30;
break;
case 2:
if (((year % 4 == 0) &&
!(year % 100 == 0))
|| (year % 400 == 0))
numDays = 29;
else
numDays = 28;
break;
default:
System.out.println("Invalid month.");
break;
}
System.out.println("Number of Days = "
+ numDays);
}
}
This is the output from the code:
Number of Days = 29
Using Strings in switch Statements
In Java SE 7 and later, you can use a String object in the switch statement's expression. The following code example, StringSwitchDemo, displays the number of the month based on the value of the String named month:
public class StringSwitchDemo {
public static int getMonthNumber(String month) {
int monthNumber = 0;
if (month == null) {
return monthNumber;
}
switch (month.toLowerCase()) {
case "january":
monthNumber = 1;
break;
case "february":
monthNumber = 2;
break;
case "march":
monthNumber = 3;
break;
case "april":
monthNumber = 4;
break;
case "may":
monthNumber = 5;
break;
case "june":
monthNumber = 6;
break;
case "july":
monthNumber = 7;
break;
case "august":
monthNumber = 8;
break;
case "september":
monthNumber = 9;
break;
case "october":
monthNumber = 10;
break;
case "november":
monthNumber = 11;
break;
case "december":
monthNumber = 12;
break;
default:
monthNumber = 0;
break;
}
return monthNumber;
}
public static void main(String[] args) {
String month = "August";
int returnedMonthNumber =
StringSwitchDemo.getMonthNumber(month);
if (returnedMonthNumber == 0) {
System.out.println("Invalid month");
} else {
System.out.println(returnedMonthNumber);
}
}
}
The output from this code is 8.
The String in the switch expression is compared with the expressions associated with each case label as if the String.equals method were being used. In order for the StringSwitchDemo example to accept any month regardless of case, month is converted to lowercase (with the toLowerCase method), and all the strings associated with the case labels are in lowercase.
Note: This example checks if the expression in the switch statement is null. Ensure that the expression in any switch statement is not null to prevent a NullPointerException from being thrown.
The while and do-while Statements
The while statement continually executes a block of statements while a particular condition is true. Its syntax can be expressed as:
while (expression) {
statement(s)
}
The while statement evaluates expression, which must return a boolean value. If the expression evaluates to true, the while statement executes the statement(s) in the while block. The while statement continues testing the expression and executing its block until the expression evaluates to false. Using the while statement to print the values from 1 through 10 can be accomplished as in the following WhileDemo program:
class WhileDemo {
public static void main(String[] args){
int count = 1;
while (count < 11) {
System.out.println("Count is: " + count);
count++;
}
}
}
You can implement an infinite loop using the while statement as follows:
while (true){
// your code goes here
}
The Java programming language also provides a do-while statement, which can be expressed as follows:
do {
statement(s)
} while (expression);
The difference between do-while and while is that do-while evaluates its expression at the bottom of the loop instead of the top. Therefore, the statements within the do block are always executed at least once, as shown in the following DoWhileDemo program:
class DoWhileDemo {
public static void main(String[] args){
int count = 1;
do {
System.out.println("Count is: " + count);
count++;
} while (count < 11);
}
}
The for Statement
The for statement provides a compact way to iterate over a range of values. Programmers often refer to it as the "for loop" because of the way in which it repeatedly loops until a particular condition is satisfied. The general form of the for statement can be expressed as follows:
for (initialization; termination;
increment) {
statement(s)
}
When using this version of the for statement, keep in mind that:
• The initialization expression initializes the loop; it's executed once, as the loop begins.
• When the termination expression evaluates to false, the loop terminates.
• The increment expression is invoked after each iteration through the loop; it is perfectly acceptable for this expression to increment or decrement a value.
The following program, ForDemo, uses the general form of the for statement to print the numbers 1 through 10 to standard output:
class ForDemo {
public static void main(String[] args){
for(int i=1; i<11; i++){
System.out.println("Count is: " + i);
}
}
}
The output of this program is:
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
Count is: 6
Count is: 7
Count is: 8
Count is: 9
Count is: 10
Notice how the code declares a variable within the initialization expression. The scope of this variable extends from its declaration to the end of the block governed by the for statement, so it can be used in the termination and increment expressions as well. If the variable that controls a for statement is not needed outside of the loop, it's best to declare the variable in the initialization expression. The names i, j, and k are often used to control for loops; declaring them within the initialization expression limits their life span and reduces errors.
The three expressions of the for loop are optional; an infinite loop can be created as follows:
// infinite loop
for ( ; ; ) {
// your code goes here
}
The for statement also has another form designed for iteration through Collections and arrays This form is sometimes referred to as the enhanced for statement, and can be used to make your loops more compact and easy to read. To demonstrate, consider the following array, which holds the numbers 1 through 10:
int[] numbers = {1,2,3,4,5,6,7,8,9,10};
The following program, EnhancedForDemo, uses the enhanced for to loop through the array:
class EnhancedForDemo {
public static void main(String[] args){
int[] numbers =
{1,2,3,4,5,6,7,8,9,10};
for (int item : numbers) {
System.out.println("Count is: " + item);
}
}
}
In this example, the variable item holds the current value from the numbers array. The output from this program is the same as before:
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
Count is: 6
Count is: 7
Count is: 8
Count is: 9
Count is: 10
We recommend using this form of the for statement instead of the general form whenever possible.
Branching Statements
The break Statement
The break statement has two forms: labeled and unlabeled. You saw the unlabeled form in the previous discussion of the switch statement. You can also use an unlabeled break to terminate a for, while, or do-while loop, as shown in the following BreakDemo program:
class BreakDemo {
public static void main(String[] args) {
int[] arrayOfInts =
{ 32, 87, 3, 589,
12, 1076, 2000,
8, 622, 127 };
int searchfor = 12;
int i;
boolean foundIt = false;
for (i = 0; i < arrayOfInts.length; i++) {
if (arrayOfInts[i] == searchfor) {
foundIt = true;
break;
}
}
if (foundIt) {
System.out.println("Found " + searchfor + " at index " + i);
} else {
System.out.println(searchfor + " not in the array");
}
}
}
This program searches for the number 12 in an array. The break statement, shown in boldface, terminates the for loop when that value is found. Control flow then transfers to the statement after the for loop. This program's output is:
Found 12 at index 4
An unlabeled break statement terminates the innermost switch, for, while, or do-while statement, but a labeled break terminates an outer statement. The following program, BreakWithLabelDemo, is similar to the previous program, but uses nested for loops to search for a value in a two-dimensional array. When the value is found, a labeled break terminates the outer for loop (labeled "search"):
class BreakWithLabelDemo {
public static void main(String[] args) {
int[][] arrayOfInts = {
{ 32, 87, 3, 589 },
{ 12, 1076, 2000, 8 },
{ 622, 127, 77, 955 }
};
int searchfor = 12;
int i;
int j = 0;
boolean foundIt = false;
search:
for (i = 0; i < arrayOfInts.length; i++) {
for (j = 0; j < arrayOfInts[i].length;
j++) {
if (arrayOfInts[i][j] == searchfor) {
foundIt = true;
break search;
}
}
}
if (foundIt) {
System.out.println("Found " + searchfor + " at " + i + ", " + j);
} else {
System.out.println(searchfor + " not in the array");
}
}
}
This is the output of the program.
Found 12 at 1, 0
The break statement terminates the labeled statement; it does not transfer the flow of control to the label. Control flow is transferred to the statement immediately following the labeled (terminated) statement.
The continue Statement
The continue statement skips the current iteration of a for, while , or do-while loop. The unlabeled form skips to the end of the innermost loop's body and evaluates the boolean expression that controls the loop. The following program, ContinueDemo , steps through a String, counting the occurences of the letter "p". If the current character is not a p, the continue statement skips the rest of the loop and proceeds to the next character. If it is a "p", the program increments the letter count.
class ContinueDemo {
public static void main(String[] args) {
String searchMe = "peter piper picked a " + "peck of pickled peppers";
int max = searchMe.length();
int numPs = 0;
for (int i = 0; i < max; i++) {
// interested only in p's
if (searchMe.charAt(i) != 'p')
continue;
// process p's
numPs++;
}
System.out.println("Found " + numPs + " p's in the string.");
}
}
Here is the output of this program:
Found 9 p's in the string.
To see this effect more clearly, try removing the continue statement and recompiling. When you run the program again, the count will be wrong, saying that it found 35 p's instead of 9.
A labeled continue statement skips the current iteration of an outer loop marked with the given label. The following example program, ContinueWithLabelDemo, uses nested loops to search for a substring within another string. Two nested loops are required: one to iterate over the substring and one to iterate over the string being searched. The following program, ContinueWithLabelDemo, uses the labeled form of continue to skip an iteration in the outer loop.
class ContinueWithLabelDemo {
public static void main(String[] args) {
String searchMe = "Look for a substring in me";
String substring = "sub";
boolean foundIt = false;
int max = searchMe.length() -
substring.length();
test:
for (int i = 0; i <= max; i++) {
int n = substring.length();
int j = i;
int k = 0;
while (n-- != 0) {
if (searchMe.charAt(j++) != substring.charAt(k++)) {
continue test;
}
}
foundIt = true;
break test;
}
System.out.println(foundIt ? "Found it" : "Didn't find it");
}
}
Here is the output from this program.
Found it
The return Statement
The last of the branching statements is the return statement. The return statement exits from the current method, and control flow returns to where the method was invoked. The return statement has two forms: one that returns a value, and one that doesn't. To return a value, simply put the value (or an expression that calculates the value) after the return keyword.
return ++count;
The data type of the returned value must match the type of the method's declared return value. When a method is declared void, use the form of return that doesn't return a value.
return;
The Classes and Objects lesson will cover everything you need to know about writing methods.
Summary of Control Flow Statements
The if-then statement is the most basic of all the control flow statements. It tells your program to execute a certain section of code only if a particular test evaluates to true. The if-then-else statement provides a secondary path of execution when an "if" clause evaluates to false. Unlike if-then and if-then-else, the switch statement allows for any number of possible execution paths. The while and do-while statements continually execute a block of statements while a particular condition is true. The difference between do-while and while is that do-while evaluates its expression at the bottom of the loop instead of the top. Therefore, the statements within the do block are always executed at least once. The for statement provides a compact way to iterate over a range of values. It has two forms, one of which was designed for looping through collections and arrays
Questions and Exercises: Control Flow Statements
Questions
1. The most basic control flow statement supported by the Java programming language is the ___ statement.
2. The ___ statement allows for any number of possible execution paths.
3. The ___ statement is similar to the while statement, but evaluates its expression at the ___ of the loop.
4. How do you write an infinite loop using the for statement?
5. How do you write an infinite loop using the while statement?
Exercises
1. Consider the following code snippet.
2. if (aNumber >= 0)
3. if (aNumber == 0)
4. System.out.println("first string");
5. else System.out.println("second string");
6. System.out.println("third string");
a. What output do you think the code will produce if aNumber is 3?
b. Write a test program containing the previous code snippet; make aNumber 3. What is the output of the program? Is it what you predicted? Explain why the output is what it is; in other words, what is the control flow for the code snippet?
c. Using only spaces and line breaks, reformat the code snippet to make the control flow easier to understand.
d. Use braces, { and }, to further clarify the code
Answers to Questions and Exercises: Control Flow Statements
Answers to Questions
1. The most basic control flow statement supported by the Java programming language is the if-then statement.
2. The switch statement allows for any number of possible execution paths.
3. The do-while statement is similar to the while statement, but evaluates its expression at the bottom of the loop.
4. Question: How do you write an infinite loop using the for statement?
Answer:
for ( ; ; ) {
}
5. Question: How do you write an infinite loop using the while statement?
Answer:
while (true) {
}
Exercises
1. Consider the following code snippet.
2. if (aNumber >= 0)
3. if (aNumber == 0)
4. System.out.println("first string");
5. else
6. System.out.println("second string");
7. System.out.println("third string");
a. Exercise: What output do you think the code will produce if aNumber is 3?
Solution:
second string
third string
b. Exercise: Write a test program containing the previous code snippet; make aNumber 3. What is the output of the program? Is it what you predicted? Explain why the output is what it is. In other words, what is the control flow for the code snippet?
Solution: NestedIf
second string
third string
3 is greater than or equal to 0, so execution progresses to the second if statement. The second if statement's test fails because 3 is not equal to 0. Thus, the else clause executes (since it's attached to the second if statement). Thus, second string is displayed. The final println is completely outside of any if statement, so it always gets executed, and thus third string is always displayed.
c. Exercise: Using only spaces and line breaks, reformat the code snippet to make the control flow easier to understand.
Solution:
if (aNumber >= 0)
if (aNumber == 0)
System.out.println("first string");
else
System.out.println("second string");
System.out.println("third string");
d. Exercise: Use braces { and } to further clarify the code and reduce the possibility of errors by future maintainers of the code.
Solution:
if (aNumber >= 0) {
if (aNumber == 0) {
System.out.println("first string");
} else {
System.out.println("second string");
}
}
System.out.println("third string");
Pertemuan 6 sd. 11 (12 JP)
3.2. Memahami struktur algoritma serta menganalisis data dalam suatu algoritma percabangan.
4.2. Menggunakan algoritma percabangan untuk memecahkan permasalahan.
Pertemuan 12 sd. 17 (10 JP)
3.3. Memahami struktur algoritma serta menganalisa data dalam suatu algoritma perulangan.
4.3. Memecahkan permasalahan dengan algoritma perulangan.