ソース貼り付け2


宿題スレPart53>>145

jpg変換のところは相当強引な処理をしています.

   // GraphicConverter.java
   import java.awt.geom.AffineTransform;
   import java.awt.image.AffineTransformOp;
   import java.awt.image.BufferedImage;
   import java.io.BufferedReader;
   import java.io.File;
   import java.io.IOException;
   import java.io.InputStreamReader;
   import java.util.Iterator;
   import javax.imageio.IIOImage;
   import javax.imageio.ImageIO;
   import javax.imageio.ImageWriteParam;
   import javax.imageio.ImageWriter;
   import javax.imageio.plugins.jpeg.JPEGImageWriteParam;
   import javax.imageio.stream.ImageOutputStream;
   public class GraphicConverter {
       public static void main(String[] args) {
           // コマンドライン引数が「1つまたは2つ」でなかった場合は使用法を出力して終了.
           if( args.length != 2 && args.length != 1 ) {
               usage();
           }
           // コマンドライン引数が2つで2番目が一文字でなかった場合は使用法を出力して終了.
           if( args.length == 2 && args[1].length() != 1 ) {
               usage();
           }
           // 変換後ファイルのデフォルトはJPG.
           char option = 'J';
           // 変換後ファイルの拡張子が指定された場合はそれに従う.
           if( args.length == 2 ) {
               option = args[1].charAt(0);
               // 変換後ファイルの指定が不正な場合は使用法を出力して終了.
               if( option != 'B' && option != 'b' 
                   && option != 'J' && option != 'j' && option != 'P' && option != 'p' ) {
                   usage();
               }
           }
           File inputFile = new File( args[0] );
           new GraphicConverter().process( inputFile, option );
       }
       /**
        * 
        * @param inputFile 入力画像ファイル
        * @param option 変換オプション
        */
       private void process(File inputFile, char option) {
           try {
               BufferedImage inBi = ImageIO.read( inputFile );
               if( inBi == null ) throw new IOException( "読み込み時に例外発生. 画像ファイルじゃないとか..." );
               System.out.println( "読み込み完了. " + inputFile.getName() + "を読み込みました." );
               System.out.println( "読み込んだ画像のサイズ: " + inBi.getWidth() + "x" + inBi.getHeight() );
               // 縮小/拡大率
               int percent = -1;
               String line = null;
               BufferedReader br = new BufferedReader( new InputStreamReader(System.in) );
               while( percent <= 0 || percent > 500 ) {
                   System.out.print( "変換後のサイズの大きさ(1〜500[%])を指定してください.\n> " );
                   line = br.readLine();
                   try {
                       percent = Integer.parseInt( line );
                   } catch( NumberFormatException nfe ) {
                       System.out.println( "整数に変換できません...:" + line );
                   }
               }
               // 変換後ファイルの幅と高さ
               int newWidth = inBi.getWidth()*percent/100;
               int newHeight= inBi.getHeight()*percent/100;
               BufferedImage outBi = new BufferedImage( newWidth, newHeight, BufferedImage.TYPE_INT_RGB );
               outBi.createGraphics().drawImage( inBi, createResizeAffine(percent/100.0), 0, 0 );
               System.out.println( "変換後の画像のサイズ: " + newWidth + "x" + newHeight );
               // 変換後ファイル名(拡張子除く)は変換前ファイル名と同じにする.
               String fileName = inputFile.getName().substring( 0, inputFile.getName().indexOf(".") );
               // 変換後ファイルを正常に書き込んだかどうか
               boolean isWrited = false;
               // 変換後ファイル名(拡張子含む)
               String fileFullName = null;
               // bmpかpngに書き込むときはImageIO.write()を使う.
               // jpgに書き込むときはサイズの上限を訊いてImageWriterを使う.
               if( option == 'B' || option == 'b' ) {
                   fileFullName = fileName + ".bmp";
                   if( new File(fileFullName).exists() ) throw new IOException( "書き込もうとしているファイルと同じ名前のファイルがすでに存在しているので書き込みません..." );
                   isWrited = ImageIO.write( outBi, "bmp", new File( fileFullName ) );
               } else if( option == 'J' || option == 'j' ) {
                   fileFullName = fileName + ".jpg";
                   if( new File(fileFullName).exists() ) throw new IOException( "書き込もうとしているファイルと同じ名前のファイルがすでに存在しているので書き込みません..." );
                   // 変換後のjpgファイルのサイズ(キロバイト)
                   int sizeKB = -1;
                   String line2 = null;
                   BufferedReader br2 = new BufferedReader( new InputStreamReader(System.in) );
                   while( sizeKB <= 0 ) {
                       System.out.print( "変換後のjpgファイルのサイズの上限([KB])を指定してください.\n> " );
                       line2 = br2.readLine();
                       try {
                           sizeKB = Integer.parseInt(line2);
                       } catch( NumberFormatException nfe ) {
                           System.out.println( "整数に変換できません...:" + line2 );
                       }
                   }
                   // 試しに書き込んだjpgファイルのサイズ
                   int size = sizeKB*1024;
                   // 圧縮レベル
                   double quality = 1.0;
                   // jpgを書いては消しての繰り返し.このループはツライ.
                   while( true ) {
                       ImageWriter imageWriter = null;
                       Iterator imageWriterIterator = ImageIO.getImageWritersByFormatName("jpg");
                       if( imageWriterIterator.hasNext() ) {
                           imageWriter = (ImageWriter) imageWriterIterator.next();
                       }
                       if( imageWriter == null ) {
                           System.err.println("JPEGImageWriter not found.");
                           System.exit(1);
                       }
                       ImageOutputStream ios = ImageIO.createImageOutputStream( new File(fileFullName) );
                       imageWriter.setOutput( ios );
                       IIOImage iioImage = new IIOImage( outBi, null, null );
                       ImageWriteParam iwp = new JPEGImageWriteParam(null);
                       iwp.setCompressionMode( ImageWriteParam.MODE_EXPLICIT );
                       iwp.setCompressionQuality( (float)quality );
                       imageWriter.write( null, iioImage, iwp );
                       ios.close();    // finallyで書くのマンドクセ('A`)
                       imageWriter.dispose();
                       File file = new File( fileFullName );
                       size = (int)file.length();
                       // 指定されたファイルサイズの上限を下回った場合はループを抜ける.
                       if( size < sizeKB*1024 ) {
                           System.out.println( "圧縮レベル→" + quality );
                           System.out.println( "変換後jpgファイルサイズ→" + size + "bytes" );
                           isWrited = true;
                           break;
                       }
                       // 指定されたファイルサイズの上限以上だった場合は
                       // 試しに書き込んだjpgファイルを消す.
                       file.delete();
                       // 圧縮レベルを少し落とす.
                       quality -= 0.01;    // TODO 処理が遅いと感じるときはこの幅を大きくする.
                   }
               } else if( option == 'P' || option == 'p' ) {
                   fileFullName = fileName + ".png";
                   if( new File(fileFullName).exists() ) throw new IOException( "書き込もうとしているファイルと同じ名前のファイルがすでに存在しているので書き込みません..." );
                   isWrited = ImageIO.write( outBi, "png", new File( fileFullName ) );
               } else {
                   System.out.println( "ありえないんですけど..." );
               }
               if( isWrited ) {
                   System.out.println( "書き込み完了. " + fileFullName +  "に書き込みました." );
               } else {
                   System.out.println( fileFullName + "に書き込めませんでした..." );
               }
           } catch( IOException e ) {
               e.printStackTrace();
           }
       }
       private AffineTransformOp createResizeAffine( double rate ) {
           double[] mtrx = { rate, 0, 0, rate };
           return new AffineTransformOp( new AffineTransform(mtrx), AffineTransformOp.TYPE_NEAREST_NEIGHBOR);
       }
       private static void usage() {
           System.out.println( "使い方:java GraphicConverter 変換元画像ファイル名 変換後ファイルタイプ" );
           System.out.println( "# 変換後ファイルタイプは(b)mp, (j)pg, (p)ngの先頭一文字を指定すること." );
           System.exit(1);
       }
   }

宿題スレPart53>>113

   // Assignment_2 .java
   import TerminalIO.*;
   class Assignment_2 {
       public static void main(String[] args) {
           CD[] cds = null;
           KeyboardReader reader = new KeyboardReader();
           String menu; //The multiline menu
           char menuOption; //The user's menu selection
           //Build the menu string
           menu = "\n*********************************************"
                + "\n*  Welcome to Crystal Clear's music store   *"
                + "\n*********************************************"
                + "\n* Please Select On of the following Option: *"
                + "\n*        A) Add CD                          *"
                + "\n*        C) Calculate the Discount          *"
                + "\n*        D) Display the Customer            *"
                + "\n*        E) Exit                            *"
                + "\n*********************************************"
                + "\nYour choice is: ";
           //Set up the menu loop
           menuOption = 'F';
           while( menuOption != 'E' && menuOption != 'e' ) {
               //Display the menu and get the user's option
               menuOption = reader.readChar(menu);
               System.out.println("");
               //Determine which menu option has been selected
               if( menuOption == 'A' || menuOption == 'a' ) {
                   if( cds == null || cds.length == 0 ) {
                       cds = new CD[1];
                   } else {
                       CD[] oldCDs = cds;
                       int length = oldCDs.length;
                       cds = new CD[length+1];
                       for( int i=0; i<length; i++ ) {
                           cds[i] = oldCDs[i];
                       }
                   }
                   CD cd = new CD();
                   cds[cds.length-1] = cd;
               } else if( menuOption == 'C' || menuOption == 'c' ) {
                   double allDiscount = 0.0;
                   for( int i=0; i<cds.length; i++ ) {
                       allDiscount += cds[i].getDiscount();
                       if( i != cds.length-1 ) {
                           System.out.print( "$" + cds[i].getDiscount() + " + " );
                       } else {
                           System.out.print( "$" + cds[i].getDiscount() + "\n= " );
                       }
                   }
                   System.out.println( "$" + allDiscount );
               } else if( menuOption == 'D' || menuOption == 'd' ) {
                   for( int i = 0; i < cds.length; i++ ) {
                       System.out.println("CD Title    : " + cds[i].getTitle());
                       System.out.println("Artist      : " + cds[i].getArtist());
                       System.out.println("Classificatnion : " + cds[i].getClassification());
                       System.out.println("Original cost   : $" + cds[i].getOriginalPrice());
                       System.out.println("Discount    : $" + cds[i].getDiscount());
                       System.out.println("Final Price     : $" + (cds[i].getOriginalPrice() - cds[i].getDiscount()) );
                       System.out.println();
                   }
               } else if( menuOption != 'E' && menuOption != 'e' ) {
                   //Invalid option
                   System.out.println("Invalid option");
               }
           }
       }
   }
   // CD.java
   import TerminalIO.*;
   class CD {
       KeyboardReader reader = new KeyboardReader();
       private String title;
       private String artist;
       private char classification;
       private double originalPrice;
       private double discount;
       public CD() {
           setTitle();
           setArtist();
           setClassification();
           setOriginalPrice();
           setDiscount();
       }
       private void setTitle() {
           title = reader.readLine("Enter the title of CD	:");
       }
       public String getTitle() {
           return title;
       }
       private void setArtist() {
           artist = reader.readLine("Enter the name of artist:");
       }
       public String getArtist() {
           return artist;
       }
       private void setClassification() {
           classification = reader.readChar("Enter the classification:");
           while( (classification != ('P')) && (classification != ('p')) && (classification != ('C')) && (classification != ('c'))
                   && (classification != ('J')) && (classification != ('j')) && (classification != ('R')) && (classification != ('r')) ) {
               System.out.println("Classification is not correct. choose from P, C, J or R");
               classification = reader.readChar("Enter the Classification: ");
           }
       }
       public char getClassification() {
           return classification;
       }
       private void setOriginalPrice() {
           originalPrice = reader.readDouble("Enter the original price ($)	:");
       }
       public double getOriginalPrice() {
           return originalPrice;
       }
       private void setDiscount() {
           discount = reader.readDouble("Enter the discount ($)   :");
           while( discount > originalPrice ) {
               System.out.println( "Discount が Original Price よりも大きい的なメッセージを出力.." );
               discount = reader.readDouble("Enter the discount ($)   :");
           }
       }
       public double getDiscount() {
           return discount;
       }
   }

宿題スレPart53>>108

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Random;

public class Q{
 public Q(){
   int t=0;int f=0;
   for(int i=0;i<100;i++){
     if(question(i+1))t++;
     else f++;
   }
   System.out.println("正解:"+t+"問,間違い:"+f+"問");
 }
 private boolean question(int no){
   Random rd=new Random();
   int a=rd.nextInt(1000);
   int b=rd.nextInt(1000);
   if(rd.nextInt(2)==0){
     while(true){
       System.out.println("No."+no+" "+a+"+"+b+"="+(a+b)+" ? (y/n)");
       String ans=scan();
       if(ans==null)continue;
       if(ans.equals("y"))return true;
       else if(ans.equals("n"))return false;
     }
   }else{
     int p=0;
     while(true){
       p=rd.nextInt(2000);
       if(p!=a+b)break;
     }
     while(true){
       System.out.println("No."+no+" "+a+"+"+b+"="+(p)+" ? (y/n)");
       String ans=scan();
       if(ans==null)continue;
       if(ans.equals("n"))return true;
       else if(ans.equals("y"))return false;
     }
   }
 }
 private String scan(){
   try {
     String str;
     BufferedReader d = new BufferedReader(new InputStreamReader(System.in));
     return d.readLine();
   } catch (IOException e) {
     return null;
   }
 }
 public static void main(String[] argv){
   new Q();
 }
}

宿題スレPart53>>87

package studyA;
public class A1 {
 public static void main(String[] argv){
   System.out.println("Hello Java");
 }
}
package studyA;
public class A2 {
 public static void main(String[] argv){
   if(argv.length>=1)System.out.println(argv[0]);
   else System.out.println("error");
 }
}
package studyA;
public class A3 {
 public static void main(String[] argv){
   if(argv.length>=1){
     if(argv[0].length()>=3)System.out.println("すこし");
     else System.out.println("たくさん");
   }else{
     System.out.println("error");
   }
 }
}
package studyA;

public class A4 {
 public static void main(String[] argv){
   if(argv.length>=1){
     if(argv[0].length()<=3){
       StringBuffer sb=new StringBuffer();
       for(int i=0;i<20;i++)sb.append(argv[0]);
       System.out.println(sb.toString());
     }else{
       System.out.println(argv[0]);
     }
   }else{
     System.out.println("error");
   }
 }
}
package studyA;
public class A5 {
 public static void main(String[] argv){
   if(argv.length>=2){
     int a,b;
     try{
       a=Integer.parseInt(argv[0]);
       b=Integer.parseInt(argv[1]);
       System.out.println(argv[0]+"+"+argv[1]+"="+(a+b));
     }catch(Exception e){
       System.out.println("error");
       return;
     }
   }else{
     System.out.println("error");
   }
 }
}
package studyA;
import java.util.Calendar;
public class A6 {
 public static void main(String[] argv){
   Calendar now=Calendar.getInstance();
   int yy=now.get(Calendar.YEAR);
   int mm=now.get(Calendar.MONTH)+1;
   int dd=now.get(Calendar.DATE);
   int hh=now.get(Calendar.HOUR);
   int min=now.get(Calendar.MINUTE);
   int ss=now.get(Calendar.SECOND);
   int bb=now.get(Calendar.DAY_OF_WEEK);
   String[] week=new String[]{"日","月","火","水","木","金","土"};
   System.out.println(yy+"年 "+mm+"月 "+dd+"日("+week[bb-1]+") "+hh+"時 "+mm+" 分"+ss+"秒");
   
 }
}
package studyA;

import java.util.Calendar;

public class A7 {
 public static void main(String[] argv){
   if(argv.length>=2){
     try{
       int yy=Integer.parseInt(argv[0]);
       int mm=Integer.parseInt(argv[1]);
       Calendar now=Calendar.getInstance();
       now.set(yy,mm-1,1,0,0,0);
       Calendar nxt=Calendar.getInstance();
       int yn=mm==12?yy+1:yy;
       int mn=mm==12?1:mm+1;
       nxt.set(yn,mn-1,1,0,0,0);
       long sa=nxt.getTimeInMillis()-now.getTimeInMillis();
       System.out.println(yy+"年"+mm+"月は"+(sa/1000/60/60/24)+"日");
     }catch(Exception e){
       System.out.println("error");
     }
   }else{
     System.out.println("error");
   }
 }
}

宿題スレPart53>>52

	// ExReadWriteDemo1.java
	import java.io.BufferedReader;
	import java.io.BufferedWriter;
	import java.io.File;
	import java.io.FileReader;
	import java.io.FileWriter;
	import java.io.IOException;
	import java.text.SimpleDateFormat;
	import java.util.GregorianCalendar;
	public class ExReadWriteDemo1 {
		public static final File file = new File("Ex.txt");
		StringBuffer writeBuffer = new StringBuffer();
		public static void main(String[] args) {
			ExReadWriteDemo1 self = new ExReadWriteDemo1();
			self.read();
			self.write();
		}
		public void read() {
			try {
				BufferedReader br = new BufferedReader( new FileReader(file) );
				String line;
				while( (line=br.readLine()) != null ) {
					writeBuffer.append( line + "\n" );
				}
				System.out.println( "読み込み完了..." );
			} catch( IOException ioe ) {
				ioe.printStackTrace();
			}
		}
		public void write() {
			BufferedWriter bw = null;
			try {
				bw = new BufferedWriter( new FileWriter(file) );
				bw.write( writeBuffer.toString() );
				SimpleDateFormat formatter = new SimpleDateFormat( "yyyy/MM/dd HH:mm:ss" );
				bw.write( "【" + formatter.format( new GregorianCalendar().getTime() ) + ":テスト】" );
				System.out.println( "書き込み完了..." );
			} catch( IOException ioe ) {
				ioe.printStackTrace();
			} finally {
				try {
					if( bw != null ) bw.close();
				} catch( IOException ioe ) {}
			}
		}
	}
	// ExReadWriteDemo2.java
	import java.io.BufferedReader;
	import java.io.File;
	import java.io.FileNotFoundException;
	import java.io.FileReader;
	import java.io.IOException;
	public class ExReadWriteDemo2 {
		public static final File file = new File("Ex.txt");
		public static void main(String[] args) {
			new ExReadWriteDemo2().process();
		}
		public void process() {
			try {
				BufferedReader br = new BufferedReader( new FileReader(file) );
				String line, bkLine = null;
				while( (line=br.readLine()) != null ) { bkLine = line; }
				System.out.println( bkLine );
			} catch( FileNotFoundException fnfe ) {
				fnfe.printStackTrace();
			} catch( IOException ioe ) {
				ioe.printStackTrace();
			}
		}
	}
	// ExReadWriteDemo3.java
	import java.io.BufferedReader;
	import java.io.BufferedWriter;
	import java.io.File;
	import java.io.FileReader;
	import java.io.FileWriter;
	import java.io.IOException;
	import java.text.SimpleDateFormat;
	import java.util.GregorianCalendar;
	public class ExReadWriteDemo3 {
		public static final File file = new File("Ex.txt");
		StringBuffer writeBuffer = new StringBuffer();
		int count = 0;
		public static void main(String[] args) {
			ExReadWriteDemo3 self = new ExReadWriteDemo3();
			self.read();
			self.write();
		}
		public void read() {
			try {
				BufferedReader br = new BufferedReader( new FileReader(file) );
				String line;
				while( (line=br.readLine()) != null ) {
					if( line.matches( "【" + "\\d{4}" + "/" + "\\d{2}" + "/" + "\\d{2}" + " " + "\\d{2}:" + "\\d{2}:" + "\\d{2}:処理" + "\\d+" + "回目" + "】" ) ) {
						count++;
					}
					writeBuffer.append( line + "\n" );
				}
				System.out.println( "読み込み完了..." );
			} catch( IOException ioe ) {
				ioe.printStackTrace();
			}
		}
		public void write() {
			BufferedWriter bw = null;
			try {
				bw = new BufferedWriter( new FileWriter(file) );
				bw.write( writeBuffer.toString() );
				SimpleDateFormat formatter = new SimpleDateFormat( "yyyy/MM/dd HH:mm:ss" );
				bw.write( "【" + formatter.format( new GregorianCalendar().getTime() ) + ":処理" + (count+1) + "回目】" );
				System.out.println( "書き込み完了..." );
			} catch( IOException ioe ) {
				ioe.printStackTrace();
			} finally {
				try {
					if( bw != null ) bw.close();
				} catch( IOException ioe ) {}
			}
		}
	}
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

今日の16件

人気の30件

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