ソース貼り付け


宿題スレPart53>>23 Access

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Vector;
public class Q23 {
 private static DateFormat df=new SimpleDateFormat("yyyyMMdd");
 private DB db=new DB();
 void kadai1()throws Exception{
   Person p=new Person();
   p.setId(1);
   p.setName("ギコ");
   p.setBirthday(df.parse("20050816"));
   p.setSex(1);
   p.setJob("ニート");
   db.insert(p);
 }
 void kadai2(String file)throws Exception{
   BufferedReader br=null;
   br=new BufferedReader(new InputStreamReader(new FileInputStream(file)));
   String line;
   Vector pp=new Vector();
   Person p=null;
   while((line=br.readLine())!=null){
     try{
       String[] s=line.split(",");
       p=getPerson(s);
       db.insert(p);
     }catch(Exception e){
       db.delete(pp);
       throw new Exception("insert error");
     }
     pp.addElement(p);
   }
   br.close();
 }
 void kadai3()throws Exception{
   ResultSet rs=db.select();
   while(rs.next()){
     int no = rs.getInt("id");
     String name = rs.getString("name");
     String birthday = rs.getString("birtyday");
     int sex= rs.getInt("sex");
     String job=rs.getString("job");
     System.out.println(no+","+name+","+birthday+","+sex+","+job);
   }
 }
 private Person getPerson(String[] s)throws Exception{
   Person p=new Person();
   if(!s[1].equals("1") && !s[1].equals("2"))throw new Exception("invalid value");
   p.setId(Integer.parseInt(s[0]));
   p.setName(s[1]);
   p.setBirthday(df.parse(s[2]));
   p.setSex(Integer.parseInt(s[3]));
   p.setJob(s[4]);
   return p;
 }
 
 static class DB{
   ResultSet select()throws Exception{
     Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
     Connection con = DriverManager.getConnection("jdbc:odbc:test");
     Statement stmt = con.createStatement();
     String sql="select * from member order by sex,birthday";
     ResultSet rs = stmt.executeQuery(sql);
     stmt.close();
     con.close();
     return rs;
   }
   void delete(Vector p)throws Exception{
     Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
     Connection con = DriverManager.getConnection("jdbc:odbc:test");
     Statement stmt = con.createStatement();
     for(int i=0;i<p.size();i++){
       String sql="delete from member where id="+((Person)p.elementAt(i)).getId();
       try{
         ResultSet rs = stmt.executeQuery(sql);
       }catch(Exception e){}
     }
     stmt.close();
     con.close();
   }
   void insert(Person p)throws Exception{
     Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
     Connection con = DriverManager.getConnection("jdbc:odbc:test");
     Statement stmt = con.createStatement();
     
     String sql="insert into member values("+p.getId()+",'"+p.getName()+"','"+df.format(p.getBirthday())+"',"+
     p.getSex()+",'"+p.getJob()+"')";
     ResultSet rs = stmt.executeQuery(sql);
     stmt.close();
     con.close();
   }
 }
 static class Person {
   Date getBirthday() {
     return birthday;
   }
   void setBirthday(Date birthday) {
     this.birthday = birthday;
   }
   int getId() {
     return id;
   }
   void setId(int id) {
     this.id = id;
   }
   String getJob() {
     return job;
   }
   void setJob(String job) {
     this.job = job;
   }
   String getName() {
     return name;
   }
   void setName(String name) {
     this.name = name;
   }
   int getSex() {
     return sex;
   }
   void setSex(int sex) {
     this.sex = sex;
   }
   int getAge(){
     Date now=new Date();
     return (int)((birthday.getTime()-now.getTime())/100/60/60/24/365);
   }
   private int id;
   private String name;
   private Date birthday;
   private int sex;
   private String job;
 }
}

宿題スレPart53>>31

   public class TreeNode {
   // private data
   private Object data;
   private TreeNode left;
   private TreeNode right;
   public TreeNode(Object initValue, 
                   TreeNode initLeft, TreeNode initRight) {
       this.data = initValue;
       this.left = initLeft;
       this.right = initRight;
   }
   public TreeNode(Object initValue) {  
       this(initValue, null, null);
   }
   public TreeNode() {  
       this(null, null, null);
   }
   /**
    * このツリー構成にitemが含まれているかどうかを調べますゴルァ
    * @param item
    * @return itemが含まれていればtrue なければfalse
    */
   public boolean contains(Object item)
   {
   	//このノードの要素と等しいならtrue
   	if(this.equals(item)) return true;
   	//そうでなかったら左右のツリーを調査
   	boolean out = false;
   	if(this.left != null)
   		out = out | this.left.contains(item);
   	if(this.right != null)
   		out = out | this.right.contains(item);
   	return out;
   }
   /**
    * もしターゲットを見つけたらそのノードへのリファレンスをリターン、見つけなかったらnullをリターンするゴルァ
    * @param target
    * @return
    */
   public Object find(Object target)
   {
   	//このノードと等しいかどうか
   	if(this.equals(target)) return this.data;
   	
   	Object obj  = null;
   	//右
   	obj = this.left.find(target);
   	if(obj != null) return obj;
   	//左
   	obj = this.right.find(target);
   	if(obj != null) return obj;
   	//両方とも無かったらnull
   	return null;
   }
   /**
    * ターゲットをツリーから消してリターンする、もしくはnullをリターンするゴルァ
    * @param target
    * @return
    */
   public Object delete(Object target)
   {
   	//このノードと等しいかどうか
   	if (this.equals(target))
		{
   		Object obj = this.data;
			this.data = null;
			return obj;
		}
   	
   	Object obj  = null;
   	//右
   	obj = this.left.delete(target);
   	if(obj != null) return obj;
   	//左
   	obj = this.right.delete(target);
   	if(obj != null) return obj;
   	//両方とも無かったらnull
   	return null;
   }
   /**
    * ターゲットをツリーから消してtrueをリターンします、もしくはfalseをリターンしますゴルァ
    * @param target
    * @return
    */
   public boolean remove(Object target)
   {
   	//このノードと等しいかどうか
   	if (this.equals(target))
		{
			this.data = null;
			return true;
		}
   	boolean out;
   	//右
   	out = this.left.remove(target);
   	if(out) return true;
   	//左
   	out = this.right.remove(target);
   	if(out) return out;
   	//両方とも無かったらfalse
   	return false;
   }
   /**
    * 構文木を先行順にするゴルァ
    * @return
    */
   public String preOrder()
   {
   	//inOrder()と同じじゃないの?
       StringBuffer text = new StringBuffer();
       if (left != null)
           text.append(left.inOrder());
       text.append(" " + getData().toString());;
       if (right != null)
           text.append(right.inOrder());
       return text.toString();        
   }
   /**
    * 構文木を後行順にするゴルァ
    * @return
    */
   public String postOrder()
   {
       StringBuffer text = new StringBuffer();
       if (right != null)
           text.append(right.postOrder());
       text.append(" " + getData().toString());;
       if (left != null)
           text.append(left.postOrder());
       return text.toString();        
   }
   public Object getData() { return data; }
   public TreeNode getLeft() { return left; }
   public TreeNode getRight() { return right; }
   public void setData(Object theNewValue) { data = theNewValue; }
   public void setLeft(TreeNode theNewLeft) { left = theNewLeft; }
   public void setRight(TreeNode theNewRight) { right = theNewRight; }
   public boolean equals(Object obj) {
       if (!(obj instanceof TreeNode))
           return false;
       TreeNode other = (TreeNode) obj;
       if (data != other.data)
           return false;
       if (left == null && right == null) // leaf
           return other.left == null && other.right == null;
       if (left == null) // right-side tree
           return other.left == null && right.equals(other.right);
       if (right == null) // left-sided tree
           return other.right == null && left.equals(other.left);
       // two-sided tree
       return left.equals(other.left) && right.equals(other.right);
   }
   public boolean insert(Comparable obj) {
       int val;
       if (getData() == null)
           setData(obj);
       try {
           val = obj.compareTo(getData());
       }
       catch (ClassCastException e) {
           return false;
       }
       if (val < 0) { 
           if (left == null) {
               setLeft(new TreeNode(obj));
           }
           else left.insert(obj);
       } 
       else if (val > 0) { 
           if (right == null) {
               setRight(new TreeNode(obj));
           }
           else right.insert(obj);
       } 
       else { // val = 0
           return false;
       }
       return true;
   }
   public String inOrder(){
       StringBuffer text = new StringBuffer();
       if (left != null)
           text.append(left.inOrder());
       text.append(" " + getData().toString());;
       if (right != null)
           text.append(right.inOrder());
       return text.toString();        
   }
   public String toString() {
       return inOrder();
   }

}

宿題スレPart53>>26

   // TestComputer.java
   import java.util.ArrayList;
   import javax.swing.JOptionPane;
   public class TestComputer {
       public static void main(String[] args) {
           String[] option = new String[] { "デスクトップ", "ノートブック", };
           int answer1 = JOptionPane.showOptionDialog(null, "デスクトップですかノートブックですか?", null, JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null, option, null );
           int answer2 = JOptionPane.showOptionDialog(null, "CPUは?", null, JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null, Computer.getProcesorTypeNames(), null );
           int answer3 = JOptionPane.showOptionDialog(null, "CDドライブは?", null, JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null, Computer.getCdDriveTypeNames(), null );
           Computer computer;
           // デスクトップ
           if( answer1 == 0 ) {
               int answer5 = JOptionPane.showOptionDialog(null, "モニターは?", null, JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null, DeskTop.getMonitorTypeNames(), null );
               ArrayList optionArrayList = new ArrayList();
               for( int i=0 ;i<DeskTop.optionTypeList.length; i++ ) {
                   if( JOptionPane.showConfirmDialog(null, "オプション\n" + DeskTop.optionTypeList[i].getName() + "は付けますか?", null, JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE ) == 0) {
                       optionArrayList.add( DeskTop.optionTypeList[i] );
                   }
               }
               Item[] optionList = (Item[])optionArrayList.toArray(new Item[0]);
               computer = new DeskTop( answer2, answer3, answer5, optionList );
           // ノートブック
           } else if( answer1 == 1 ) {
               int answer4 = JOptionPane.showOptionDialog(null, "モニターは?", null, JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null, NoteBook.getMonitorTypeNames(), null );
               computer = new NoteBook( answer2, answer3, answer4 );
           } else {
               computer = null;
               throw new IllegalArgumentException();
           }
           System.out.println( computer );
       }
   }
   // Computer.java
   public abstract class Computer {
       public static final Item[] processorType = new Item[] {
               new Item("CPU 0.8GB", 100),
               new Item("CPU 1.0GB", 130),
               new Item("CPU 1.2GB", 150),
               new Item("CPU 1.5GB", 200),
       };
       public static final Item[] cdDriveType = new Item[] {
               new Item("CD-R Drive",  40),
               new Item("CD-RW Drive", 80),
               new Item("DVD Drive",  100),
       };
       private Item processor;
       private Item cdDrive;
       public Computer(int processorPosition, int cdDrivePosition) {
           this.processor = processorType[processorPosition];
           this.cdDrive = cdDriveType[cdDrivePosition];
       }
       public String toString() {
           return processor.toString() + cdDrive.toString();
       }
       public static String[] getProcesorTypeNames() {
           String[] processorTypeNames = new String[processorType.length];
           for( int i=0; i<processorType.length; i++ ) {
               processorTypeNames[i] = processorType[i].getName();
           }
           return processorTypeNames;
       }
       public static String[] getCdDriveTypeNames() {
           String[] cdDriveTypeNames = new String[cdDriveType.length];
           for( int i=0; i<cdDriveType.length; i++ ) {
               cdDriveTypeNames[i] = cdDriveType[i].getName();
           }
           return cdDriveTypeNames;
       }
       public int sum() {
           return processor.getPrice() + cdDrive.getPrice();
       }
   }
   // DeskTop.java
   public class DeskTop extends Computer{
       public static final Item[] monitorType = new Item[] {
               new Item("15 inch monitor", 50),
               new Item("17 inch monitor", 80),
               new Item("19 inch monitor", 100),
       };
       private Item monitor;
       public static final Item[] optionTypeList = new Item[] {
           new Item("Modem", 60),
           new Item("NetWork Card", 60),
           new Item("Zip Drive", 40),
       };
       private Item[] optionList;
       public DeskTop(int processorPosition, int cdDrivePosition, int monitorPosition, Item[] optionList) {
           super(processorPosition, cdDrivePosition);
           this.monitor = monitorType[monitorPosition];
           this.optionList = optionList;
       }
       public static String[] getMonitorTypeNames() {
           String[] monitorTypeNames = new String[monitorType.length];
           for( int i=0; i<monitorType.length; i++ ) {
               monitorTypeNames[i] = monitorType[i].getName();
           }
           return monitorTypeNames;
       }
       public String toString() {
           StringBuffer message = new StringBuffer();
           message.append( "デスクトップ型パソコン\n" );
           message.append( super.toString() );
           message.append( monitor.toString() );
           for(int i=0; i<optionList.length; i++) {
               message.append( optionList[i].toString() );
           }
           message.append( "----------------------\n" );
           message.append( "\t小計: $" + sum() );
           return message.toString();
       }
       public int sum() {
           int sum = super.sum() + monitor.getPrice();
           for( int i=0; i<optionList.length; i++ ) {
               sum += optionList[i].getPrice();
           }
           return sum;
       }
   }
   // NoteBook.java
   public class NoteBook extends Computer {
       public static final Item[] monitorType = new Item[] {
               new Item("14 inch monitor", 40),
               new Item("15 inch monitor", 70),
       };
       private Item monitor;
       public NoteBook(int processorPosition, int cdDrivePosition, int monitorPosition) {
           super(processorPosition, cdDrivePosition);
           this.monitor = monitorType[monitorPosition];
       }
       public static String[] getMonitorTypeNames() {
           String[] monitorTypeNames = new String[monitorType.length];
           for( int i=0; i<monitorType.length; i++ ) {
               monitorTypeNames[i] = monitorType[i].getName();
           }
           return monitorTypeNames;
       }
       public String toString() {
           return "ノートブック型パソコン\n" + super.toString() + monitor.toString() 
           + "----------------------\n" + "\t小計: $" + sum();
       }
       public int sum() {
           return super.sum() + monitor.getPrice();
       }
   }
   // Item.java
   public class Item {
       private String name;
       private int price;
       public Item(String name, int price) {
           this.name = name;
           this.price = price;
       }
       public String getName() {
           return name;
       }
       public int getPrice() {
           return price;
       }
       public String toString() {
           return "\t" + name + ": $" + price + "\n";
       }
   }

宿題スレPart52>>752

	// BreadMachineApp.java
	import javax.swing.JOptionPane;
	public class BreadMachineApp {
		public BreadMachineApp() {
		}
		public static void main(String[] args) {
			BreadMachine breadMachine = new BreadMachine();
			// パンの種類を聞く。
			String breadType = JOptionPane.showInputDialog("What type of bread, [w]hite or [s]weet?");
			if( breadType.equals( "w" ) ) breadMachine.setBreadType( BreadMachine.BREAD_TYPE_WHITE );
			else if( breadType.equals( "s" ) ) breadMachine.setBreadType( BreadMachine.BREAD_TYPE_SWEET );
			else throw new IllegalArgumentException("I_L_L_E_G_A_L   B_R_E_A_D   T_Y_P_E!!");
			// パンの型のサイズが2倍かどうかを聞く。
			if( readBoolean("Is the frame size double?") ) breadMachine.setIsTwiceSize( true );
			else breadMachine.setIsTwiceSize( false );
			// 焼き方はマニュアルかどうかを聞く。
			if( readBoolean("Is the baking manual?") ) breadMachine.setIsManual( true );
			else breadMachine.setIsManual( false );
			System.out.println(breadMachine);
		}
		/**
		 * 引数に与えられたメッセージを持つYes/No(はい/いいえ)プロンプトを表示し、
		 * Yesが選択されたか否かを返却する。
		 * 
		 * @param prompt メッセージ
		 * @return Yesが選択されたか否か。Yesが選択された場合がtrue。
		 */
		public static boolean readBoolean(String prompt) {
			int twicelF = JOptionPane.showConfirmDialog(null, prompt, null, JOptionPane.YES_NO_OPTION );
			return twicelF == 0;
		}
	}
	// BreadMachine.java
	import javax.swing.JOptionPane;
	public class BreadMachine {
		/**
		 * パンの種類
		 */
		private String breadType;
		/**
		 * パンの種類がwhiteを表す定数
		 */
		public static final String BREAD_TYPE_WHITE = "white";
		/**
		 * パンの種類がsweetを表す定数
		 */
		public static final String BREAD_TYPE_SWEET = "sweet";
		/**
		 * パンの型のサイズが2倍かどうか
		 */
		private boolean isTwiceSize;
		/**
		 * 焼き方はマニュアルかどうか
		 */
		private boolean isManual;
		/**
		 * 所要時間管理テーブル
		 * 1列目:作業名
		 * 2列目:パンの種類がwhiteの場合の所要時間
		 * 3列目:パンの種類がsweetの場合の所要時間
		 * 4列目:パンの型のサイズが2倍の時に所要時間も2倍にしないとダメな場合はtrue
		 */
		public static final Object[][] costTimeTable = new Object[][] {
	//		                      white sweet
			{ "Primary Kneading",   15, 20, false, },
			{ "Secondary Kneading", 18, 33, false, },
			{ "Loaf Shaping",        2,  2, false, },
			{ "Baking",             45, 35, true,  },
			{ "Cooling",            30, 30, false, },
		};
		public BreadMachine() {
		}
		public void setBreadType(String breadType) { this.breadType = breadType; }
		public void setIsTwiceSize(boolean isTwiceSize) { this.isTwiceSize = isTwiceSize; }
		public void setIsManual(boolean isManual) { this.isManual = isManual; }
		public String getBreadType() { return breadType; }
		public boolean isTwiceSize() { return isTwiceSize; }
		public boolean isManual() { return isManual; }
		public String toString() {
			StringBuilder messageBuilder = new StringBuilder();
			messageBuilder.append(
					"パンの種類:" + breadType + "\n"
			      + "サイズ:" + (isTwiceSize ? "型の2倍" : "型と同じ") + "\n"
			      + "焼き方:" + (isManual ? "マニュアル" : "○○") + "\n"	// TODO
			);
			for( int i=0; i<costTimeTable.length; i++ ) {
				String processName = (String)costTimeTable[i][0];
				int costTime = Integer.MIN_VALUE;
				// パンの種類がwhiteの場合
				if( breadType.equals( BreadMachine.BREAD_TYPE_WHITE ) ) {
					costTime = getCostTime( (Integer)costTimeTable[i][1], (Boolean)costTimeTable[i][3] );
				// パンの種類がsweetの場合
				} else if( breadType.equals( BreadMachine.BREAD_TYPE_SWEET ) ) {
					costTime = getCostTime( (Integer)costTimeTable[i][2], (Boolean)costTimeTable[i][3] );
				}
				JOptionPane.showMessageDialog( null, processName + "を" + costTime + "分でやりましたよ。", null, JOptionPane.YES_OPTION );
				messageBuilder.append( processName + ":\t" + costTime + "min.\n" );
				if( ((String)costTimeTable[i][0]).equals( "Loaf Shaping" ) && isManual ) {
					JOptionPane.showMessageDialog( null, "パンのドウを動かしなさいよ。", null, JOptionPane.YES_OPTION );
				}
			}
			return messageBuilder.toString();
		}
		private int getCostTime(int time, boolean mustTwice) {
			if( isTwiceSize && mustTwice ) time *= 2;
			return time;
		}
	}
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

今日の8件

人気の30件

  • counter: 6651
  • today: 1
  • yesterday: 0
  • online: 1