Mahasiswa2.java
========================================================================
import java.io.*;
class Mahasiswa2{
String nim,nama;
void setNIM(String nim){
this.nim = nim;
}
void setNama(String nama){
this.nama = nama;
}
String getNIM(){
return nim;
}
String getNama(){
return nama;
}
void simpan(){
FileWriter fw = null;
try {
fw = new FileWriter("Mahasiswa.txt",true);
fw.write(nim +";" + nama +"\r\n");
}catch (Exception ex) {
System.out.println("Tidak dapat menyimpan data ke dalam file");
} finally {
if (fw !=null){
try {
fw.close();
} catch (Exception ex) {}
}
}
}
boolean baca(int noRecord){
FileReader fr = null;
String data = "";
boolean ada = true;
try{
fr = FileReader("Mahasiswa.txt");
br = BufferedReader(fr);
int no = 0;
while ((no++ <= noRecord) && ((data = br.readLine()) != null));
} catch (Exception ex) {
System.out.println("Tidak dapat membaca data");
} finally {
if (fr !=null) {
try {
fr.close();
}catch (Exception ex) {}
}
}
if ((data == null) || (data.equals(""))) ada = false;
if (ada) {
String nimTmp = "";
int i=0;
while ((i < data.length()) && (data.charAt(i) != ';')) {
nimTmp = nimTmp + data.substring(i, i+1);
i++;
}
nim = nimTmp;
nama = data.substring(i+1, data.length());
}
return ada;
}
}
========================================================================
DataMahasiswa.java
========================================================================
import java.util.Scanner;
class DataMahasiswa {
public static void main(String args[]){
Scanner baca = new Scanner (System.in);
Mahasiswa mahasiswa = new Mahasiswa();
int pilih = -1;
String intNim, intNama;
do {
System.out.println("Menu pilihan :");
System.out.println("1. Menyimpan Data");
System.out.println("2. Menampilkan Data");
System.out.println("0. Selesai");
System.out.println("Menu dipilih :"); pilih = baca.nextInt();
System.out.println("");
switch (pilih){
case 0: System.out.println("Selesai"); break;
case 1: System.out.println("Ketik data yang akan disimpan");
System.out.println("NIM :"); inNim = baca.nextLine();
inNim = baca.nextLine();
System.out.println("Nama :"); inNama = baca.nextLine();
mahasiswa.setNim(inNim);
mahasiswa.setNama(inNama);
mahasiswa.simpan();
break;
case 2: System.out.println("Data yang tersimpan adalah:");
int i=0;
while (mahasiswa.baca(i++)) {
System.out.println("Data ke-"+i);
System.out.println("NIM : "+mahasiswa.getNim());
System.out.println("Nama : "+mahasiswa.getNama());
}
break;
default: System.out.println("Menu yang dipilih tidak terdaftar");
}
System.out.println();
}while (ppilih != 0);
}
}
}
Tidak ada komentar