วันอังคารที่ 29 มีนาคม พ.ศ. 2554

โปรแกรมคำนวณภาษี

import java.util.*;
import java.io.*;
import org.apache.poi.hssf.usermodel.*;

public class TaxCalc {
  public static void main(String[] args) {
    double income = readDouble(new Scanner(System.in),"เงินได้สุทธิ : ");
    try {
      double[][] taxTable = getTaxTable("c:/java101/tax.xls");
      double tax = calcTax(taxTable, income);
      System.out.println("ภาษี = " + tax);
    } catch (FileNotFoundException e) {
      System.out.println("ไม่พบแฟ้ม: " + e.getMessage());
    } catch (IOException e) {
      System.out.println(e.getMessage());
    }     
  }
  private static double[][] getTaxTable(String excelFile)
                     throws FileNotFoundException, IOException {
    double[][] table = new double[0][0];
    HSSFWorkbook wb = new HSSFWorkbook(
                            new FileInputStream(excelFile));
    HSSFSheet sheet = wb.getSheetAt(0);
    int rows = sheet.getPhysicalNumberOfRows() - 1;
    table = new double[rows][2];
    for (int i = 1; i <= rows; i++) {
      HSSFRow r = sheet.getRow(i);
      HSSFCell cell = r.getCell((short) 0);
      table[i-1][0] = cell.getNumericCellValue();
      cell = r.getCell((short) 1);
      table[i-1][1] = cell.getNumericCellValue();
    }
    return table;
  }   
  public static double calcTax(double[][] taxTable, double income) {
    double tax = 0.0;
    for (int i = 0; i < taxTable.length && income > 0; i++) {
      tax += Math.min(income,taxTable[i][0]) * taxTable[i][1];
      income -= taxTable[i][0];
    }
    return tax;
  }
  // เพิ่ม readDouble ของรหัสที่ 10-1 ที่นี่ 

ไม่มีความคิดเห็น:

แสดงความคิดเห็น