Blog ini saya buat untuk share contoh-contoh program java sederhana. Semoga bermanfaat
Selasa, 24 April 2012
membaca input dari file
import java.io.*;
import java.util.*;
public class Main {
public static void main (String[] args)throws FileNotFoundException {
try {
double n1, n2, n3;
String n;
Scanner fileInput = new Scanner(new FileReader("nilai.txt"));
PrintWriter outFile = new PrintWriter("hasil.out");
System.out.println("mulai scanner file");
try {
while (fileInput.hasNext()) {
String line = fileInput.nextLine();
Scanner lineScan = new Scanner(line);
lineScan.useDelimiter(";");
n = lineScan.next();
n1 = lineScan.nextDouble();
n2 = lineScan.nextDouble();
n3 = lineScan.nextDouble();
double average=(n1+n2+n3)/3;
outFile.println(n+";"+average);
} } catch (Exception e) {
System.out.println("scan file error");
}
fileInput.close();
outFile.close();
System.out.println("berhasil scanner file, hasil output akan dicetak di hasil.txt");
} catch (FileNotFoundException fnfex) {
System.out.println("File does not exist!!");
}
}
}
matriks orthogonal
import java.util.Scanner;
public class array
{
public static void main(String[] args) {
//deklarasi variabel array dan penciptaan
Double array[][]=new Double [2][2];
Scanner scan=new Scanner(System.in);
System.out.println("Masukkan nilai matriks baris 1 kolom 1: ");
array[0][0]=scan.nextDouble();
System.out.println("Masukkan nilai matriks baris 1 kolom 2: ");
array[0][1]=scan.nextDouble();
System.out.println("Masukkan nilai matriks baris 2 kolom 1: ");
array[1][0]=scan.nextDouble();
System.out.println("Masukkan nilai matriks baris 2 kolom 2: ");
array[1][1]=scan.nextDouble();
kalkulator sederhana (handling exception)
import java.util.*;
public class kalkulator
{
// method operasi kali
public int kali(int a, int b){
int c= a*b;
return c;
}
// method operasi bagi
public float bagi(float a, float b){
float c= a/b;
return c;
}
//method operasi pangkat
public int pangkat(int a, int b){
int c=(int) Math.pow(a,b);
return c;
}
Langganan:
Postingan (Atom)