SourcePost_________


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

宿題スレPart71 >>463への解答 自動販売機

// P71_463.java
import java.util.*;

public class P71_463 {

    private static final String INVALID_MONEY = "硬貨、紙幣の金額が異常です。";
    private static final String INVALID_OPERATION = "不正な操作です。";
    private static final String SHORT_OF_MONEY = "お金が足りません。";
    
    private int type;
    private int money;
    private Map<Integer, Map<String, Integer>> prices;
    
    private P71_463() {
        prices = new LinkedHashMap<Integer, Map<String, Integer>>();
        Map<String, Integer> mp1 = new LinkedHashMap<String, Integer>();
        mp1.put("ミネラルウォーター", 100);
        mp1.put("コーヒー", 120);
        mp1.put("500mlペットボトルジュース", 150);
        Map<String, Integer> mp2 = new LinkedHashMap<String, Integer>();
        mp2.put("発泡酒", 140);
        mp2.put("ビール", 200);
        Map<String, Integer> mp3 = new LinkedHashMap<String, Integer>();
        mp3.put("マイルドセブン", 410);
        mp3.put("マイルドセブン プライム スーパーライトボックス", 440);
        prices.put(1, mp1);
        prices.put(2, mp2);
        prices.put(3, mp3);
    }

    private void nyukin() {
        int money = 0;
        for( ; ; ) {
            System.out.print("お金を入れてください。硬貨、紙幣(1000円札のみ)両方使えます。0で入力完了です。> ");
            Scanner sc = new Scanner(System.in);
            try {
                money = sc.nextInt();
                switch(money) {
                    case 0:
                        return;
                    case 10:
                    case 50:
                    case 100:
                    case 500:
                    case 1000:
                        this.money += money;
                        System.out.printf("現在の入金額: %d円%n", this.money);
                        break;
                    default:
                        money = 0;
                        System.out.println(INVALID_MONEY);
                        break;
                }
            } catch(InputMismatchException ex) {
                System.out.println(INVALID_MONEY);
            }
        }
    }

    private void konyu() {
        int what = -1;
        System.out.println("何を買いますか? 0でキャンセルします。");
        Map<String, Integer> map = prices.get(type);
        String[] keys = map.keySet().toArray(new String[0]);
        int len = keys.length;
        for(int i=0; i<map.size(); i++) {
            System.out.printf("%d: %s: %d円%n", i+1, keys[i], map.get(keys[i]));
        }
        System.out.print("> ");
        Scanner sc = new Scanner(System.in);
        try {
            what = sc.nextInt();
            if(what == 0) {
                return;
            } else if(!(1 <= what && what <= len) ) {
                System.out.println(INVALID_OPERATION);
            } else {
                String str = keys[what-1];
                int price = map.get(str);
                if(money < price) {
                    System.out.println(SHORT_OF_MONEY);
                } else {
                    System.out.printf("%sを買いました。%n", keys[what-1]);
                    money -= price;
                }
                System.out.printf("現在の入金額: %d円%n", this.money);
            }
            konyu();
        } catch(InputMismatchException ex) {
            System.out.println(INVALID_OPERATION);
        }
    }

    private int setType() {
        int type = -1;
        for( ; ; ) {
            System.out.print("自販機のタイプを選択してください(1: ジュース, 2: アルコール: 3, タバコ)> ");
            Scanner sc = new Scanner(System.in);
            try {
                type = sc.nextInt();
                if(!( 1 <= type && type <= 3 )) {
                    System.out.println(INVALID_OPERATION);
                } else { this.type = type; break; }
            } catch(InputMismatchException ex) {
                System.out.println(INVALID_OPERATION);
            }
        }
        return type;
    }

    private void henkin() {
        System.out.printf("%d円返金します。", this.money);
        this.money = 0;
    }
    
    private void exit() {
        henkin();
        System.out.println("ありがとうございました。");
        System.exit(0);
    }
    
    private void doWhat() {
        int what = -1;
        for( ; ; ) {
            System.out.print("何をしますか? 0: 終了, 1: 購入, 2: 入金, 3: 自販機のタイプ変更> ");
            Scanner sc = new Scanner(System.in);
            try {
                what = sc.nextInt();
                switch(what) {
                    case 0: exit(); break;
                    case 1: konyu(); break;
                    case 2: nyukin(); break; 
                    case 3: setType(); break;
                    default: System.out.println(INVALID_OPERATION); break;
                }
            } catch(InputMismatchException ex) {
                System.out.println(INVALID_OPERATION);
            }
        }
    }
    
    private void solve() {
        this.type = setType();
        nyukin();
        System.out.printf("現在の入金額: %d円%n", this.money);
        doWhat();
    }

    public static void main(String[] args) {
        new P71_463().solve();
    }
}

宿題スレPart71 >>438への解答 サイコロとじゃんけんでコンピュータとバトルするゲーム

// P71_438.java
import java.util.*;

public class P71_438 {
    Character plr, cpu;
    private void printStatus() {
        System.out.printf("%s\tHP: %d, 攻撃力: %d%n", plr.getName(), plr.getHp(), plr.getPow());
        System.out.printf("%s\tHP: %d, 攻撃力: %d%n", "CPU",         cpu.getHp(), cpu.getPow());
        System.out.println();
    }
    
    private Character[] printHand() {
        Hand h1 = plr.getHand();
        Hand h2 = cpu.getHand();
        System.out.printf("%s: %s\tCPU: %s%n", plr.getName(), h1.getName(), h2.getName());
        Hand h = Hand.judge(h1, h2);
        if(h == null) { System.out.println("引き分け"); }
        else { System.out.printf("%sの勝ち!!%n", h==h1 ? plr.getName() : cpu.getName()); }
        System.out.println();
        if(h == null) { return null; }
        Character[] ret = h==h1 ? new Character[] { plr, cpu } : new Character[] { cpu, plr };
        return ret;
    }
    
    private int getDiceCount(int dices) {
        int ret = 0;
        for(int i=0; i<dices; i++) {
            ret += (int)(Math.random()*6) + 1;
        }
        return ret;
    }
    
    // chs[0]: winner, chs[1]: loser
    private void printDamage(Character[] chs) {
        System.out.println("サイコロをふります。");
        int win = 0, lose = 0;
        if((int)(Math.random()*33) == 0) {
            System.out.println("キングぼ○びー登場!!! 勝者のサイコロが10コになります!!!");
            win = getDiceCount(10);
        } else if((int)(Math.random()*50) == 0) {
            System.out.println("肉のカーテン発動!!!");
            System.out.printf("敗者の%sのHPが0に!!%n", chs[1].getName());
            chs[1].setHp(0);
            return;
        } else {
            win = getDiceCount(2);
        }
        lose = getDiceCount(1);
        int hit = win - lose < 0 ? 0 : win - lose;
        if(chs[0].equals(plr)) {
            System.out.printf("勝者の%sの出目: %d, 敗者の%sの出目: %d%n", plr.getName(), win, cpu.getName(), lose);
            int damage = hit*plr.getPow();
            System.out.printf("ダメージ計算 %d x %d = %d%n", plr.getPow(), hit, damage);
            if(damage <= 0) { System.out.println("ミス!! 攻撃が外れた!!"); }
            else { System.out.printf("%sに%dのダメージを与えた!%n", cpu.getName(), damage); }
            cpu.subHp(damage);
            if(cpu.getHp() <= 0) { cpu.setHp(0); }
        } else { 
            System.out.printf("敗者の%sの出目: %d, 勝者の%sの出目: %d%n", plr.getName(), lose, cpu.getName(), win);
            int damage = hit*cpu.getPow();
            System.out.printf("ダメージ計算 %d x %d = %d%n", cpu.getPow(), hit, damage);
            if(damage <= 0) { System.out.println("ミス!! 攻撃が外れた!!"); }
            else { System.out.printf("%sに%dのダメージを与えた!%n", plr.getName(), damage); }
            plr.subHp(damage);
            if(plr.getHp() <= 0) { plr.setHp(0); }
        }
        System.out.println();
    }
    
    private void sleep(int time) {
        try {
            Thread.sleep(time);
        } catch(InterruptedException ex) {
            // nop
        }
    }
    
    private void doIt() {
        System.out.print("あなたの名前を入力してください: ");
        Scanner sc = new Scanner(System.in);
        String name = sc.nextLine();
        this.plr = new Character(name,  true,  (int)(Math.random()*30) + 1000, (int)(Math.random()*10) + 5);
        this.cpu = new Character("CPU", false, (int)(Math.random()*30) + 1000, (int)(Math.random()*10) + 5);
        for( ; ; ) {
            printStatus();
            System.out.println("じゃんけん...");
            sleep(2000);
            System.out.println("ポイ!!");
            int plh = (int)(Math.random()*3);
            int cph = (int)(Math.random()*3);
            plr.setHand(Hand.HANDS[plh]);
            cpu.setHand(Hand.HANDS[cph]);
            Character[] chs = printHand();
            sleep(2000);
            if(chs == null) { continue; }
            // chs[0]: winner, chs[1]: loser
            printDamage(chs);
            sleep(2000);
            if(plr.getHp() == 0 || cpu.getHp() == 0) { printStatus(); break; }
        }
        if(plr.getHp() == 0 && cpu.getHp() == 0) { System.out.println("結果: 引き分け"); }
        else if(plr.getHp() == 0) { System.out.printf("結果: %sの勝ち%n", cpu.getName()); }
        else { System.out.printf("結果: %sの勝ち%n", plr.getName()); }
    }

    public static void main(String[] args) {
        new P71_438().doIt();
    }
}
// Character.java
import java.util.*;
import static java.lang.Math.*;

public class Character {
    private boolean isPlayer;
    private String name;
    private int hp;
    private int pow;
    private Hand hand;
    public Character(String name, boolean isPlayer, int hp, int pow) {
        this.name = name;
        this.isPlayer = isPlayer;
        this.hp = hp;
        this.pow = pow;
    }
    // getters
    public Hand getHand() { return hand; }
    public String getName() { return name; }
    public int getHp() { return hp; }
    public int getPow() { return pow; }
    
    // setters
    public void setHp(int hp) { this.hp = hp; }
    public void setHand(Hand hand) { this.hand = hand; }
    public void subHp(int hp) { this.hp -= hp; }
}
// Hand.java
public class Hand {
    private String name;
    private int id;
    private Hand(String name, int id) {
        this.name = name;
        this.id   = id;
    }
    public static Hand g = new Hand("グー",   0);
    public static Hand c = new Hand("チョキ", 1);
    public static Hand p = new Hand("パー",   2);
    public static final Hand[] HANDS = new Hand[] { g, c, p, };
    
    public static Hand judge(Hand h1, Hand h2) {
        if((h1.id - h2.id + 3)%3 == 2) { return h1; }
        if((h1.id - h2.id + 3)%3 == 1) { return h2; }
        return null;
    }
    public String getName() { return name; }
}

宿題スレPart71 >>380への解答 名簿情報出力

// P71_380.java
public class P71_380 {
    private static final int NUM = 5;
    public static void main(String[] args) {
        StudentInfo[] si = new StudentInfo[NUM];
        si[0] = new StudentInfo("長野せりな", 13, 5, "04-1313-1313");
        si[1] = new StudentInfo("朝日奈央",   15, 5, "048-515-1515");
        si[2] = new StudentInfo("大川藍",     20, 6, "06-2020-2020");
        si[3] = new StudentInfo("橋本楓",     21, 3, "045-121-2121");
        si[4] = new StudentInfo("倉田瑠夏",   22, 3, "06-2222-2222");
        si[0].setId(27);
        si[0].setTelno("04-3131-3131");
        for(int i=0; i<NUM; i++) {
            System.out.println(si[i]);
        }
    }
}
// StudentInfo.java
public class StudentInfo {
    private String name, telno;
    private int id, grade;
    public StudentInfo(String name, int id, int grade, String telno) {
        this.name = name;
        this.id   = id;
        this.grade = grade;
        this.telno = telno;
    }
    
    @Override public String toString() {
        return this.name + ":" + this.id + ":" + this.grade + ":" + this.telno;
    }
    
    public void setId(int id) { this.id = id; }
    public void setTelno(String telno) { this.telno = telno; }
}

宿題スレPart61 >>15への回答 ISBN LEX

むしゃくしゃして作った。 いまは後悔している。

$ java ISBNLex sample.txt

ISBNLex.java

//ISBNLex.java
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.util.Map;
import java.util.HashMap;
import java.util.Iterator;
 import java.util.StringTokenizer;

import java.util.regex.*;


class ISBNLex {
    Map<String,String> m_mapPubCode;
    Map<String,Integer> m_mapPubCount;
    
    public static void main(String[] argv) throws Exception {

	ISBNLex isbn = new ISBNLex();

	isbn.loadPublisherCode("publisher.txt");

	System.out.println("--- ISBN list ---");
	isbn.readFile(argv[0]);

	System.out.println("--- Publisher Statics ---");
	isbn.showPubCount();
    }
    
    public void showPubCount() {
	Iterator it = m_mapPubCode.keySet().iterator();
	while(it.hasNext()) {
	    String pub = (String)it.next();
	    String name = m_mapPubCode.get(pub);
	    int count = m_mapPubCount.get(pub);
	    System.out.println(name + " " + count);
	}
    }

    public void readFile(String filename) throws Exception {
	BufferedReader br = new BufferedReader(new FileReader(filename));
	while(true) {
	    String line = br.readLine();
	    if(line == null) break;
	    analyzeLine(line);
	}
    }
    
    public void analyzeLine(String line) throws Exception {
	Pattern p = Pattern.compile("ISBN 4-([0-9]+?)-([0-9]+?)-([0-9xX])");
	Matcher m = p.matcher(line);
	m.reset();
	while(m.find()) {
	    
	    String pub   = m.group(1);
	    String item  = m.group(2);
	    String check = m.group(3);
	    
	    System.out.println(" ISBN 4-"+pub+"-"+item+"-"+check);
	    
	    Integer count = m_mapPubCount.get(pub);
	    if(count!=null) {
		m_mapPubCount.put(pub,Integer.valueOf(count.intValue()+1));
	    }
	}
    }
    
    public void loadPublisherCode(String filename) throws Exception {
	m_mapPubCode  = new HashMap<String,String>();
	m_mapPubCount = new HashMap<String,Integer>();
	BufferedReader br = new BufferedReader(new FileReader(filename));
	while(true) {
	    String line = br.readLine();
	    if(line == null) break;
	    StringTokenizer t = new StringTokenizer(line,",");
	    String code = t.nextToken();
	    String name = t.nextToken();
	    m_mapPubCode.put(code,name);
	    m_mapPubCount.put(code,0);
	}
    }
}

publisher.txt

00,岩波書店
01,旺文社
02,朝日新聞社
13,東京大学出版会
621,丸善
657,早稲田大学出版部
7561,アスキー出版局
7664,慶應義塾大学出版会
7828,産業図書
8443,インプレス

sample.txt

プログラミング言語処理系 コンパイラ C言語 ISBNコード
プログラミングISBN 4-7560-1926-3 入門C言語
ISBN 4-621-0399-7 コンパイラ
ISBN 4-00-010345-8 プログラミング言語処理系 
プログラミングISBN 4-62-03999-7 コンパイラ
ISBN 4-7561-126-31 入門C言語
ISBN 4-00-01345-8 プログラミング言語処理系
ISBN 4-00-010345-18 プログラミング言語処理系 
プログラミングISBN 4-7664-321-7 入門C言語
ISBN 4-01-01345-8 プログラミング言語処理系 
プログラミングISBN 4-7828-50507-3 コンパイラ
ISBN 4-7664-325-0 入門C言語ISBN 4-7828-505-3 コンパイラ
ISBN コードISBN 4-02-03345-8 プログラミング言語処理系
ISBN 4-7828-5057- コンパイラISBN 4-621-03999-17 コンパイラ
ISBN 4-03-123456-x プログラミング言語処理系
ISBN 4-8443-321-7 入門C言語ISBN 4-4-621-03999-7 コンパイラ
ISBN コードISBN 4-7828-5057-3 コンパイラISBN 4-8443-221-9
入門C言語ISBN 4-657-0399-7 コンパイラ 
コードISBN 4-7328-5057-3 コンパイラ
ISBN 4-7561-1926-3 入門C言語ISBN 4-788-0399-7 コンパイラ
ISBN 4-621-039999-7 コンパイラISBN 4-125-0399-7 コンパイラ

宿題スレPart60 >>984への回答 三角形の描画

3次元は投影が面倒くさそうなので他の人よろしく。

DrawTriangle?.html

<html>
  <body>
    <applet code="DrawTriangle" width=300 height=300>
    </applet>
  </body>
</html>

DrawTriangle?.java

// DrawTriangle.java

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;

public class DrawTriangle extends Applet implements AdjustmentListener {
    Image img;
    Scrollbar hscr;

    int w,h; // window size
    Graphics g_buf;
    
    int[] x = {-50,-30,50};
    int[] y = {10, -40, -20};
    int[] rgb = { 230, 20, 0 };

    int[] draw_x = new int[x.length];
    int[] draw_y = new int[y.length];

    public void init() {
	w = getSize().width;
	h = getSize().height;

	img = createImage(w,h);
	g_buf = img.getGraphics();

	hscr = new Scrollbar(Scrollbar.HORIZONTAL, 0, 10, 0, 370);
	hscr.setSize(getSize().width,getSize().height);
	hscr.addAdjustmentListener(this);

	setLayout(new BorderLayout());
	add(hscr, BorderLayout.SOUTH);

	draw();
    }

    public void update(Graphics g) {
	paint(g);
    }

    public void paint(Graphics g) {
	g.drawImage(img, 0, 0, this);
    }

    public void adjustmentValueChanged(AdjustmentEvent e) {
	if(e.getAdjustable() == hscr) {
	    draw();
	}
    }

    public void draw() {
	double theta = hscr.getValue() * Math.PI / 180;
	double c = Math.cos(theta);
	double s = Math.sin(theta);
	
	for(int i=0; i<3; ++i) {
	    draw_x[i] = (int)(c*x[i] - s*y[i]) + w / 2;
	    draw_y[i] = (int)(s*x[i] + c*y[i]) + h / 2;
	}
	
	g_buf.setColor(Color.white);
	g_buf.fillRect(0,0,w,h);
	g_buf.setColor(new Color(rgb[0],rgb[1],rgb[2]));
	g_buf.fillPolygon(draw_x, draw_y, 3);
	
	repaint();
    }
}

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

今日の1件

  • SourcePost_________(1)

人気の30件

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