SourcePost________


このページのコンテンツ一覧(5個位までにしてください。上が最新で下が最古です)

宿題スレPart60 >>978-980への回答 PayCar?クラスとChargeableCar?クラス

//PayCar.java
public class PayCar extends Car{
    private int budget;

    public PayCar() {
    	budget = 0;
    }

    public int charge(int amount) {
    	if (budgetIsEnough(amount)) {
    		budget -= amount;
    		return amount;
    	} else {
    		int paid = budget;
    		budget = 0;
    		return paid;
    	}
    }

    public int addBudget(int amount) {
    	budget += amount;
    	return budget;
    }

    public int getBudget() {
    	return budget;
    }

    private boolean budgetIsEnough(int value) {
    	return budget >= value ? true : false;
    }
}
//ChargeableCar.java
public class ChargeableCar extends Car {
    private int budget;
    private int debt;

    public ChargeableCar() {
    	budget = 0;
    	debt = 0;
    }

    public int charge(int amount) {
    	if (budgetIsEnough(amount)) {
    		budget -= amount;
    		return amount;
    	} else {
    		int paid = budget;
    		budget = 0;
    		debt += amount - paid;
    		return paid;
    	}
    }

    public int addBudget(int amount) {
    	budget += amount;
    	return budget;
    }

    public int getBudget() {
    	return budget;
    }

    public int exactDebt() {
    	if (hasDebt()) {
    		if (budgetIsEnough(debt)) {
    			int paid = debt;
    			budget -= debt;
    			debt = 0;
    			return paid;
    		} else {
    			int paid = budget;
    			budget = 0;
    			debt -= paid;
    			return paid;
    		}
    	}
    	return 0;
    }

    public int getDebt() {
    	return debt;
    }
    
    private boolean budgetIsEnough(int value) {
    	return budget >= value ? true : false;
    }

    private boolean hasDebt() {
    	return debt > 0 ? true : false;
    }
}
//実行クラス
public class ExecCarClasses {
    public static void main(String[] args) {
    	PayCar pc1 = new PayCar();
    	System.out.println("---------- PayCar 1 ----------");
    	System.out.println("your money : " + pc1.addBudget(1000));
    	System.out.println("charged : " + pc1.charge(300));
    	System.out.println("your money : " + pc1.getBudget());

    	PayCar pc2 = new PayCar();
    	System.out.println("---------- PayCar 2 ----------");
    	System.out.println("your money : " + pc2.addBudget(1000));
    	System.out.println("charged : " + pc2.charge(3000));
    	System.out.println("your money : " + pc2.getBudget());

    	ChargeableCar cc1 = new ChargeableCar();
    	System.out.println("---------- ChargeableCar 1 ----------");
    	System.out.println("your money : " + cc1.addBudget(1000));
    	System.out.println("charged : " + cc1.charge(300));
    	System.out.println("your money : " + cc1.getBudget());

    	ChargeableCar cc2 = new ChargeableCar();
    	System.out.println("---------- ChargeableCar 2 ----------");
    	System.out.println("your money : " + cc2.addBudget(1000));
    	System.out.println("charged : " + cc2.charge(3000));
    	System.out.println("your money : " + cc2.getBudget());
    	System.out.println("your debt : " + cc2.getDebt());
    	System.out.println("your money : " + cc2.addBudget(5000));
    	System.out.println("exact debt : " + cc2.exactDebt());
    }
}

宿題スレPart60 >>935への回答 インターネット時代の暗号技術 噂の公開鍵を作ってみよう

// RSA.java
import java.util.Random;

public class RSA {
    
    public static void main(String[] argv) {
	
	int[] org = new int[3];
	org[0] = 100; org[1] = 200; org[2] = 300;

	RSA rsa = new RSA();
	
	int p = rsa.getRandomPrimeNumber(1000);
	int q = rsa.getRandomPrimeNumber(1000);

	int n = p * q;
	int m = (p-1) * (q-1);
	
	int e = rsa.getKey1(m,100);
	int d = rsa.getKey2(m,e);
	
	System.out.printf("p=%d,q=%d?n",p,q);
	System.out.printf("PUBLIC KEY:e=%d,n=%d?n",e,n);
	System.out.printf("SECRET KEY:d=%d,n=%d?n",d,n);

	System.out.println("--- encrypt ---");
	int[] enc = rsa.encrypt(e, n, org);

	System.out.println("--- decrypt ---");
	int[] result = rsa.encrypt(d, n, enc);
    }

    public int extMod(int a, int b, int n) {
	long ret = a % n;
	for(int i=1; i<b; ++i) {
	    ret = (a * ret) % n;
	}
	return (int)ret;
    }
   
    public int[] encrypt(int e, int n, int[] from) {
	int[] to = new int[from.length];
	for(int i=0; i<from.length; ++i) {
	    to[i] = extMod(from[i],e,n);
	    System.out.println("" + from[i]+" => "+to[i]);
	}
	return to;
    }
   
    public int getKey1(int m, int max) {
	Random r = new Random();
	int e;
	for(e = r.nextInt(max); e == 0 || gcd(e,m) != 1; e = r.nextInt(max));
	return e;
    }

    public int getKey2(int m, int e) {
	int d; 
	int s = e;
	int t = m;
	int u = 1;
	int v = 0;
	int q, w;
	
	while( s > 0 ) {
	    q = t/s;
	    w = t - q * s;
	    t = s;
	    s = w;
	    w = v - q * u;
	    v = u;
	    u = w; 
	}
	if( v < 0 ) {
	    d = v + m;
	} else {
	    d = v;
	}
	return d;
    }
    
    public int gcd(int x, int y) {
 	int z;
	if( x < y ) {
	    int tmp = x;
	    x = y;
	    y = tmp;
	}
	
	z = x % y;
	if ( z == 0 ) return y;
	return gcd(y, x-y);
    }
    
    public int getRandomPrimeNumber(int max) {
	Random r = new Random(); 
	int n;
	for(n = r.nextInt(max); !isPrime(n); n=r.nextInt(max)) ;
	return n;
    }
    
    public boolean isPrime(int n) {
	if( n == 0 || n == 1 ) return false;
	
	int max = (int)Math.sqrt(n);
	for(int i=2; i<=max; ++i) {
	    if( n % i == 0 ) {
		return false;
	    }
	}
	return true;
    }
}

宿題スレPart60 >>365への回答 Web版アドレス帳

JBoss AS 4.0.5

   // PersonalInformation.java
   package net.ch2.pc10.homework.java.addressbook.bean;
   
   import net.ch2.pc10.homework.java.addressbook.exception.InvalidInputException;
   
   public class PersonalInformation {
       private String address;
       private String name;
       private String telNo;
       
       public PersonalInformation() {
           this.address = "";
           this.name = "";
           this.telNo = "";
       }
       
       public PersonalInformation(String address, String name, String telNo) throws InvalidInputException {
           if( address == null || name == null || telNo == null ||
                  address.length() == 0 || name.length() == 0 || telNo.length() == 0 ) {
               throw new InvalidInputException("all of the fields are mandatory.");
           }
           this.address = address;
           this.name = name;
           this.telNo = telNo;
       }
   
       public String getAddress() {
           return address;
       }
   
       public String getName() {
           return name;
       }
   
       public String getTelNo() {
           return telNo;
       }
       
       // for debugging purpose
       public String toString() {
           return address + " : " + name + " : " + telNo;
       }
   }
   // InvalidInputException.java
   package net.ch2.pc10.homework.java.addressbook.exception;
   
   public class InvalidInputException extends Exception {
       public InvalidInputException() {        
       }
       public InvalidInputException(String s){
           super(s);
       }
   }
   // SendInformationServlet.java
   package net.ch2.pc10.homework.java.addressbook.servlet;
   
   import java.io.IOException;
   import java.util.ArrayList;
   
   import javax.servlet.ServletException;
   import javax.servlet.http.HttpServletRequest;
   import javax.servlet.http.HttpServletResponse;
   import javax.servlet.http.HttpSession;
   
   import net.ch2.pc10.homework.java.addressbook.bean.PersonalInformation;
   import net.ch2.pc10.homework.java.addressbook.exception.InvalidInputException;
   
   public class SendInformationServlet extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
       public SendInformationServlet() {
           super();
       }            
       
       public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
           PersonalInformation p = null;
           try {
               p = new PersonalInformation(
                   req.getParameter("address"),
                   req.getParameter("name"),
                   req.getParameter("telNo")
               );
           } catch (InvalidInputException e) {
               res.getWriter().println( "<html><body>" + e.getMessage() + "<br>" +
                       "<a href=?"javascript:history.back();?">back</a></body></html>" );
               return;
           }
           HttpSession s = req.getSession(true);
           ArrayList list = (ArrayList)s.getAttribute("list");
           if( list == null ) list = new ArrayList();
           list.add(p);
           s.setAttribute("list", list);
           System.out.println( list );
           res.getWriter().println( "<html><body>your information was successfully inserted.<br>" +
                   "<table border=?"1?">" +
                   "<tr><td>name</td><td>" + p.getName() + "</td></tr>" +
                   "<tr><td>address</td><td>" + p.getAddress() + "</td></tr>" +
                   "<tr><td>telNo</td><td>" + p.getTelNo() + "</td></tr>" +
                   "</table>" + 
                   "<a href=?"index.jsp?">go back to menu</a></body></html>" );
       }
   }
   // ShowInformationServlet.java
   package net.ch2.pc10.homework.java.addressbook.servlet;
   
   import java.io.IOException;
   import java.io.PrintWriter;
   import java.util.ArrayList;
   import java.util.Iterator;
   
   import javax.servlet.ServletException;
   import javax.servlet.http.HttpServletRequest;
   import javax.servlet.http.HttpServletResponse;
   import javax.servlet.http.HttpSession;
   
   import net.ch2.pc10.homework.java.addressbook.bean.PersonalInformation;
   
   public class ShowInformationServlet extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
       public ShowInformationServlet() {
           super();
       }       
       
       public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
           PrintWriter out = res.getWriter();
           out.println( "<html><body>address book<br>" +
                   "<table border=?"1?"><tr><th>name</th><th>address</th><th>tel</th></tr>" );
           HttpSession s = req.getSession();
           ArrayList list = (ArrayList)s.getAttribute("list");
           for( Iterator iterator=list.iterator(); iterator.hasNext(); ) {
               PersonalInformation p = (PersonalInformation)iterator.next();
               out.println( "<tr><td>" + p.getName() + "</td>" );
               out.println( "<td>" + p.getAddress() + "</td>" );
               out.println( "<td>" + p.getTelNo() + "</td></tr>" );
           }
           out.println("</table><a href=?"index.jsp?">go back to menu</a></body></html>");
       }
   }

index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>menu</title>
</head>
<body>
<a href="input.jsp">input an information to your address book</a><br>
<a href="ShowInformation">show your address book</a><br>
</body>
</html>

input.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>input your address information</title>
</head>
<body>
<form action="SendInformation" method="POST">
<table>
<tr><td>name</td><td> <input type="text" name="name" value=""> </td></tr>
<tr><td>address</td><td> <input type="text" name="address" value=""> </td></tr>
<tr><td>tel</td><td> <input type="text" name="telNo" value=""> </td></tr>
<tr><td></td><td><input type="submit" value="send"/></td></tr>
</table>
</form>
</body>
</html>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
	<display-name>
	AddressBook</display-name>
	<servlet>
		<description>
		</description>
		<display-name>
		SendInformationServlet</display-name>
		<servlet-name>SendInformationServlet</servlet-name>
		<servlet-class>
		net.ch2.pc10.homework.java.addressbook.servlet.SendInformationServlet</servlet-class>
	</servlet>
	<servlet>
		<description>
		</description>
		<display-name>
		ShowInformationServlet</display-name>
		<servlet-name>ShowInformationServlet</servlet-name>
		<servlet-class>
		net.ch2.pc10.homework.java.addressbook.servlet.ShowInformationServlet</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>SendInformationServlet</servlet-name>
		<url-pattern>/SendInformation</url-pattern>
	</servlet-mapping>
	<servlet-mapping>
		<servlet-name>ShowInformationServlet</servlet-name>
		<url-pattern>/ShowInformation</url-pattern>
	</servlet-mapping>
	<welcome-file-list>
		<welcome-file>index.html</welcome-file>
		<welcome-file>index.htm</welcome-file>
		<welcome-file>index.jsp</welcome-file>
		<welcome-file>default.html</welcome-file>
		<welcome-file>default.htm</welcome-file>
		<welcome-file>default.jsp</welcome-file>
	</welcome-file-list>
</web-app>

宿題スレPart60 >>106への回答 四則演算アプレット

jdk_1.4.2_13

   // FourArithmeticOperationsApplet.java
   import java.awt.FlowLayout;
   import java.awt.GridLayout;
   import java.awt.event.ActionEvent;
   import java.awt.event.ActionListener;
   
   import javax.swing.JApplet;
   import javax.swing.JButton;
   import javax.swing.JComboBox;
   import javax.swing.JLabel;
   import javax.swing.JOptionPane;
   import javax.swing.JPanel;
   import javax.swing.JTextField;
   
   public class FourArithmeticOperationsApplet extends JApplet {
       private JTextField numField1, numField2;
       private JButton executeButton;
       private JComboBox comboBox;
       private JLabel resultLabel;
       
       public void init() {
           numField1 = new JTextField(5); numField2 = new JTextField(5);
           executeButton = new JButton("=");
           executeButton.addActionListener(
                   new ActionListener() {
                       public void actionPerformed(ActionEvent e) {
                           int num1 = 0, num2 = 0;
                           try {
                               num1 = Integer.parseInt(numField1.getText());
                               num2 = Integer.parseInt(numField2.getText());
                           } catch(NumberFormatException nfe) {
                               JOptionPane.showMessageDialog(numField1, nfe.getMessage());
                               return;
                           }
                           String result = null;
                           char ope = ((String)comboBox.getSelectedItem()).charAt(0);
                           switch( ope ) {
                           case '+':
                               result = String.valueOf(num1 + num2);
                               break;
                           case '-':
                               result = String.valueOf(num1 - num2);
                               break;
                           case '*':
                               result = String.valueOf(num1 * num2);
                               break;
                           case '/':
                               try {
                               result = String.valueOf(num1 / num2);
                               if( num1 % num2 != 0 ) {
                                   result += ", remainder " + (num1 % num2);
                               }
                               } catch( ArithmeticException ae ) {
                                   JOptionPane.showMessageDialog(numField1, ae.getMessage());
                                   return;
                               }
                               break;
                           default:
                               break;
                           }
                           resultLabel.setText(result);
                       }
                   }
           );
           comboBox = new JComboBox(new String[] { "+", "-", "*", "/", });
           resultLabel = new JLabel();
           resultLabel.setAlignmentX(JTextField.CENTER_ALIGNMENT);
           getContentPane().setLayout(new GridLayout(2, 1));
           JPanel p1 = new JPanel( new FlowLayout() ), p2 = new JPanel( new FlowLayout()  );
           p1.add( numField1 );
           p1.add( comboBox );
           p1.add( numField2 );
           p1.add( executeButton );
           p2.add(resultLabel);
           getContentPane().add(p1);
           getContentPane().add(p2);
           setSize(500, 100);
       }
   }

宿題スレPart60 >>101への回答 名簿

jdk1.5.0_10. 下と非常によく似た課題.

   // KaiinDemo.java
   import java.io.BufferedReader;
   import java.io.FileNotFoundException;
   import java.io.FileReader;
   import java.io.IOException;
   import java.util.Arrays;
   import java.util.StringTokenizer;
   
   public class KaiinDemo {
       private kaiin[] tbl;
   
       public KaiinDemo() {
           this.tbl = new kaiin[5];
       }
       
       public static void main(String[] args) {
           KaiinDemo self = new KaiinDemo();
           self.readFile( "data.txt" );
           System.out.println("---");
           self.showMeibo();
           System.out.println("---");
           self.sortKaiinByWeight();
           self.showMeibo();
           System.out.println("---");
       }
   
       private void showMeibo() {
           for( int i=0; i<tbl.length; i++ ) {
               tbl[i].showMeibo();
           }
       }
   
       private void sortKaiinByWeight() {
           Arrays.sort( tbl, new KaiinWeightComparator() );
       }
   
       private void readFile( final String FILE_NAME ) {
           try {
               BufferedReader br = new BufferedReader( new FileReader(FILE_NAME) );
               for( int i=0; i<tbl.length; i++ ) {
                   String str = br.readLine();
                   StringTokenizer t = new StringTokenizer( str, "," );
                   tbl[i] = new kaiin( t.nextToken(), t.nextToken().charAt(0), Integer.parseInt(t.nextToken()), Double.parseDouble(t.nextToken()) );
               }
           } catch (FileNotFoundException e) {
               e.printStackTrace();
           } catch (IOException e) {
               e.printStackTrace();
           }
       }
   }
   // kaiin.java
   public class kaiin {
   
       public static int kaiinsu = 0;
       protected String name;
       protected char sex;
       protected int age;
       protected double weight;
    
       public kaiin(){
   	name = "未登録";
   	sex = ' ';
   	age = 0;
   	weight = 0.0;
   	kaiinsu++;
   	System.out.println("オブジェクトを生成しました。");
       }
       public kaiin(String n,char s,int a,double w){
   	name = n;
   	sex = s;
   	age = a;
   	weight = w;
   	kaiinsu++;
   	System.out.println("氏名:" + name + " 性別:" + sex + " 年齢" + age + " 体重:" + weight + "で新しいオブジェクトを初期化しました。");
       }
       public void setKaiin(String n){
   	name = n;
       }
       
       public void setKaiin(char s){
   	sex = s;
       }
       
       public void setKaiin(int a){
   	age = a;
       }
       
       public void setKaiin(double w){
   	weight = w;
       }
       
       void showMeibo(){
   	System.out.println("会員の氏名は" + name);
   	System.out.println("会員の性別は" + sex);
   	System.out.println("会員の年齢は" + age);
   	System.out.println("会員の体重は" + weight);
       }
       
       public double retWeight() { return this.weight; }
   }
   // KaiinWeightComparator.java
   import java.util.Comparator;
   
   public class KaiinWeightComparator implements Comparator<kaiin> {
       public int compare(kaiin o1, kaiin o2) {
           return (int)((o1.retWeight() - o2.retWeight())*10);
       }
   }

宿題スレPart60 >>35への回答 JavaBeans?のソート

jdk1.5.0_10

   // SortDemo.java
   import java.io.BufferedReader;
   import java.io.FileNotFoundException;
   import java.io.FileReader;
   import java.io.IOException;
   import java.util.ArrayList;
   import java.util.Arrays;
   import java.util.StringTokenizer;
   
   public class SortDemo {
       private DataBean[] beans;
       
       public static void main(String[] args) {
           SortDemo self = new SortDemo();
           self.readFile( args[0] );
           self.sortBeans();
           self.showBeans();
       }
       
       private void readFile( final String FILE_NAME ) {
           ArrayList<DataBean> list = new ArrayList<DataBean>();
           try {
               BufferedReader br = new BufferedReader( new FileReader(FILE_NAME) );
               for( String line; (line=br.readLine())!=null; ) {
                   StringTokenizer tokenizer = new StringTokenizer(line, "/");
                   list.add( new DataBean( tokenizer.nextToken(), tokenizer.nextToken(), Integer.parseInt(tokenizer.nextToken()) ) );
               }
           } catch (FileNotFoundException e) {
               e.printStackTrace();
           } catch (IOException e) {
               e.printStackTrace();
           }
           beans = list.toArray( new DataBean[0] );
       }
       
       private void sortBeans() {
           Arrays.sort( beans, new DataBeanComparator() );
       }
       
       private void showBeans() {
           for( DataBean bean : beans ) 
               System.out.println( bean.getKana() + "/" + bean.getAlpha() + "/" + bean.getNumber() );
       }
   }
   // DataBean.java
   public class DataBean {
       private String kana;
       private String alpha;
       private int number;
       
       public DataBean( String kana, String alpha, int number ) {
           this.kana = kana;
           this.alpha = alpha;
           this.number = number;
       }
   
       protected String getAlpha() {
           return alpha;
       }
   
       protected String getKana() {
           return kana;
       }
   
       protected int getNumber() {
           return number;
       }
   }
   // DataBeanComparator.java
   import java.util.Comparator;
   
   public class DataBeanComparator implements Comparator<DataBean> {
       public int compare(DataBean o1, DataBean o2) {
           return o2.getNumber() - o1.getNumber();
       }
   }
written by iys

CONTENTS

最新の20件

2020-11-14 2005-12-06 2006-11-04 2012-07-15 2009-06-19 2011-03-03 2006-12-13 2007-11-05 2014-07-22 2014-07-19 2014-07-09 2014-01-14 2012-09-03 2012-03-28

今日の5件

人気の30件

  • counter: 3275
  • today: 1
  • yesterday: 0
  • online: 2