SourcePost__________


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

宿題スレPart66 >>802への回答 RSSリーダ

不要なコードもあるけど、再利用してて面倒臭いので消してません。 RSS1.0が大量に掲載されてるのがエロゲサイトしか見つからなかったので、データはそんな感じです。

   // RSSReader.java
   import javax.swing.*;
   
   public class RSSReader {
       public static void main(String[] args) {
           RSSReaderFrame frame = new RSSReaderFrame();
           frame.setBounds( 10, 10, 800, 600);
           frame.setVisible(true);
           frame.fetchData();
       }
   }
   // Channel.java
   import java.util.*;
   
   public class Channel {
       private String title;
       private String link;
       private List<Item> itemList;
   
       public Channel() {
           this.itemList = new ArrayList<Item>();
       }
   
       public String getTitle() { return this.title; }
       public void setTitle(String title) { this.title = title; }
   
       public String getLink() { return this.link; }
       public void setLink(String link) { this.link = link; }
   
       public List<Item> getItemList() { return this.itemList; }
   
       public void addItem(Item item) {
           itemList.add(item);
       }
   
       @Override public String toString() {
           StringBuilder builder = new StringBuilder();
           builder.append(title + " / " + link + " / \n");
           for(Item item : itemList) {
               builder.append("    " + item + " / ");
           }
           return builder.toString();
       }
       
   }
   // ColumnComparator.java
   import java.util.*;
   import javax.swing.*;
   
   public class ColumnComparator implements Comparator{
       final protected int index;
       final protected boolean ascending;
       public ColumnComparator(int index, boolean ascending) {
           this.index = index;
           this.ascending = ascending;
       }
       public int compare(Object one, Object two) {
           if(one instanceof Vector && two instanceof Vector) {
               Object oOne = ((Vector)one).elementAt(index);
               Object oTwo = ((Vector)two).elementAt(index);
               if(oOne==null && oTwo==null) {
                   return 0;
               }else if(oOne==null) {
                   return ascending ? -1 :  1;
               }else if(oTwo==null) {
                   return ascending ?  1 : -1;
               }else if(oOne instanceof Comparable && oTwo instanceof Comparable) {
                   Comparable cOne = (Comparable)oOne;
                   Comparable cTwo = (Comparable)oTwo;
                   return ascending ? cOne.compareTo(cTwo) : cTwo.compareTo(cOne);
               }
           }
           return 1;
       }
       public int compare(Number o1, Number o2) {
           double n1 = o1.doubleValue();
           double n2 = o2.doubleValue();
           if(n1 < n2) {
               return -1;
           }else if(n1 > n2) {
               return 1;
           }else{
               return 0;
           }
       }
   }
   // Item.java
   public class Item {
       private String title;
       private String link;
       private String dcDate;
       private String description;
   
       public Item() {}
   
       public String getTitle() { return this.title; }
       public void setTitle(String title) { this.title = title; }
   
       public String getLink() { return this.link; }
       public void setLink(String link) { this.link = link; }
   
       public String getDcDate() { return this.dcDate; }
       public void setDcDate(String dcDate) { this.dcDate = dcDate; }
   
       public String getDescription() { return this.description; }
       public void setDescription(String description) { this.description = description; }
   
       @Override public String toString() {
           return title + " / " + link + " / " + description;
       }
   }
   // MyTableModel.java
   import java.util.*;
   import java.awt.*;
   import javax.swing.*;
   import javax.swing.table.*;
   
   public class MyTableModel extends DefaultTableModel {
       private static final ColumnContext[] columnArray = {
           new ColumnContext("article title", String.class, true),
           new ColumnContext("site name", String.class,  true),
           new ColumnContext("date", String.class,  true),
       };
   
       MyTableModel(String[] columnNames, int rowNum) {
           super(columnNames, rowNum);
       }
       public Class<?> getColumnClass(int modelIndex) {
           return columnArray[modelIndex].columnClass;
       }
       public void sortByColumn(int column, boolean isAscent) {
           Collections.sort(getDataVector(), new ColumnComparator(column, isAscent));
           fireTableDataChanged();
       }
       @Override public boolean isCellEditable(int row, int column) {
           return false;
       }
       private static class ColumnContext {
           public final String  columnName;
           public final Class   columnClass;
           public final boolean isEditable;
           public ColumnContext(String columnName, Class columnClass, boolean isEditable) {
               this.columnName = columnName;
               this.columnClass = columnClass;
               this.isEditable = isEditable;
           }
       }
   }
   // RSS10Reader.java
   import java.io.File;
   import java.io.FileNotFoundException;
   import java.io.IOException;
   import java.util.Calendar;
   import java.util.Date;
   import java.util.GregorianCalendar;
   
   import javax.xml.parsers.DocumentBuilder;
   import javax.xml.parsers.DocumentBuilderFactory;
   import javax.xml.parsers.ParserConfigurationException;
   
   import org.w3c.dom.Document;
   import org.w3c.dom.Element;
   import org.w3c.dom.Node;
   import org.w3c.dom.NodeList;
   import org.xml.sax.SAXException;
   
   public class RSS10Reader {
   
       public Channel read(String url) {
           Channel c = null;
           try {
               DocumentBuilderFactory dbfactory = DocumentBuilderFactory.newInstance();
               DocumentBuilder builder = dbfactory.newDocumentBuilder();
               Document doc = builder.parse(url);
               Element root = doc.getDocumentElement();
               Element channel = (Element)(root.getElementsByTagName(RSSReaderConstant.NAME_CHANNEL).item(0));
               String title = getStringElementValue(channel, RSSReaderConstant.NAME_TITLE);
               String link = getStringElementValue(channel, RSSReaderConstant.NAME_LINK);
               c = new Channel();
               c.setTitle(title);
               c.setLink(link);
   
               NodeList itemList = root.getElementsByTagName(RSSReaderConstant.NAME_ITEM);
               for(int i=0; i<itemList.getLength(); i++) {
                   Element item = (Element)(itemList.item(i));
                   String itemTitle = getStringElementValue(item, RSSReaderConstant.NAME_TITLE);
                   String itemLink = getStringElementValue(item, RSSReaderConstant.NAME_LINK);
                   String dcDate = getStringElementValue(item, RSSReaderConstant.NAME_DC_DATE);
                   String itemDescription = getStringElementValue(item, RSSReaderConstant.NAME_DESCRIPTION);
                   Item itm = new Item();
                   itm.setTitle(itemTitle);
                   itm.setLink(itemLink);
                   itm.setDcDate(dcDate);
                   itm.setDescription(itemDescription);
                   c.addItem(itm);
               }
   
           } catch (ParserConfigurationException e) {
               e.printStackTrace();
           } catch (SAXException e) {
               e.printStackTrace();
           } catch (IOException e) {
               e.printStackTrace();
           }
           return c;
       }
   
       private static String getStringElementValue(Element root, String elementName) {
           NodeList list = root.getElementsByTagName(elementName);
           int length = list.getLength();
           if(length != 1) {
               throw new IllegalArgumentException();
           }
           return list.item(0).getTextContent();
       }
   
       private static int getIntElementValue(Element root, String elementName) {
           return Integer.parseInt(getStringElementValue(root, elementName));
       }
   
       private static Date getDateElementValue(Element root, String elementName) {
           Calendar calendar = GregorianCalendar.getInstance();
           NodeList list = root.getElementsByTagName(elementName);
           int length = list.getLength();
           if(length != 1)
               throw new IllegalArgumentException();
   
           Element element = (Element)list.item(0);
           NodeList children = element.getChildNodes();
           calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(children.item(0).getTextContent()));
           calendar.set(Calendar.MINUTE, Integer.parseInt(children.item(1).getTextContent()));
           calendar.set(Calendar.SECOND, 0);
           calendar.set(Calendar.MILLISECOND, 0);
           return calendar.getTime();
       }
   
   }
   // RSSReaderConstant.java
   public final class RSSReaderConstant {
       public static final String RSS_SITE_FILE_NAME = "rss.txt";
       public static final String LINE_SEPARATOR = System.getProperty("line.separator");
   
       public static final String NAME_CHANNEL = "channel";
       public static final String NAME_TITLE = "title";
       public static final String NAME_LINK = "link";
       public static final String NAME_ITEM = "item";
       public static final String NAME_DESCRIPTION = "description";
       public static final String NAME_DC_DATE = "dc:date";
   }
   // RSSReaderFrame.java
   import java.awt.BorderLayout;
   import java.awt.GridLayout;
   import java.io.*;
   import java.util.List;
   import java.util.ArrayList;
   import java.util.Scanner;
   import javax.swing.*;
   
   public class RSSReaderFrame extends JFrame {
       private MyTableModel model;
       private JTable table;
       private JTextArea descArea;
       private JTextArea logArea;
       private String[] columnNames = { "article title", "site name", "date", };
   
       public RSSReaderFrame() {
           this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
           this.setTitle("RSSReader");
           createLayout();
       }
   
       private void createLayout() {
           this.setLayout(new GridLayout(2, 1));
           this.model = new MyTableModel(columnNames, 0);
           this.table = new JTable(model);
           JScrollPane pane1 = new JScrollPane(table);
           JPanel p = new JPanel(new BorderLayout());
           this.descArea = new JTextArea();
           this.descArea.setText("ここにdescriptionが表示されるようにしたかったが面倒なのでヤメ。");
           this.descArea.setEditable(false);
           JScrollPane pane2 = new JScrollPane(descArea);
           p.add(pane2, BorderLayout.CENTER);
           this.logArea = new JTextArea(5, 0);
           this.logArea.setEditable(false);
           JScrollPane pane3 = new JScrollPane(logArea);
           p.add(pane3, BorderLayout.SOUTH);
           getContentPane().add(pane1);
           getContentPane().add(p);
       }
   
       public void fetchData() {
           File file = new File(RSSReaderConstant.RSS_SITE_FILE_NAME);
           Scanner scanner = null;
           try {
               scanner = new Scanner(file);
           } catch(FileNotFoundException ex) {
               ex.printStackTrace();
               return;
           }
           while(scanner.hasNext()) {
               String url = scanner.next();
               log("Fetching " + url + " ... ");
               RSS10Reader rssReader = new RSS10Reader();
               Channel c = rssReader.read(url);
               List<Item> itemList = c.getItemList();
               for(Item itm : itemList) {
                   List<Object> row = new ArrayList<Object>();
                   row.add(itm.getTitle());
                   row.add(c.getTitle());
                   row.add(itm.getDcDate());
                   model.addRow(row.toArray());
               }
               log("Sorting ... ");
               model.sortByColumn(2, false);
               logln("OK.");
           }
       }
   
       private void log(String message) {
           logArea.append(message);
       }
   
       private void logln(String message) {
           log(message + RSSReaderConstant.LINE_SEPARATOR);
       }
   }
   // rss.txt
   http://atuworks.sblo.jp/index.rdf
   http://august-soft.com/rss/august.rdf
   http://catwalkstaff.seesaa.net/index.rdf
   http://hscrowd.blog85.fc2.com/?xml
   http://blog.livedoor.jp/uye_13cm/index.rdf

宿題スレPart66 >>739への回答 ○×ゲーム

   // P66_739.java
   import java.util.*;
   
   public class P66_739 {
       public static void main(String[] args) {
           new P66_739().start();
       }
   
       int[][] field;
       char[] chars;
   
       private P66_739() {
           this.field = new int[3][3];
           this.chars = new char[] { ' ', 'O', 'X', };
       }
   
       private void start() {
           drawField();
           int counter = 0;
           while(check()) {
               turnOf(counter++ % 2 + 1);
               drawField();
           }
       }
   
       private void drawField() {
           System.out.println(" "+chars[field[0][0]]+" | "+chars[field[0][1]]+" | "+chars[field[0][2]]+" ");
           System.out.println("---+---+---");
           System.out.println(" "+chars[field[1][0]]+" | "+chars[field[1][1]]+" | "+chars[field[1][2]]+" ");
           System.out.println("---+---+---");
           System.out.println(" "+chars[field[2][0]]+" | "+chars[field[2][1]]+" | "+chars[field[2][2]]+" ");
       }
   
       private void putStone(int row, int column, int num) throws IllegalArgumentException {
           if(row < 0)    throw new IllegalArgumentException("row should be more than or equal to 0. ");
           if(row > 2)    throw new IllegalArgumentException("row should be less than or equal to 2. ");
           if(column < 0) throw new IllegalArgumentException("column should be more than or equal to 0. ");
           if(column > 2) throw new IllegalArgumentException("column should be less than or equal to 2. ");
           if(field[row][column] != 0) throw new IllegalArgumentException("you cannot put a stone here! ");
           field[row][column] = num;
       }
   
       private void turnOf(int num) {
           System.out.println("please put a stone(such as \"2[Enter]1[Enter]\"), mr./ms. " + chars[num] + "> ");
           Scanner scanner = new Scanner(System.in);
           int[] cell = new int[2];
           int counter = 0;
           while(scanner.hasNextInt()){
               cell[counter++] = scanner.nextInt();
               if(counter == 2) break;
           }
           try {
               putStone(cell[0], cell[1], num);
           } catch(IllegalArgumentException ex) {
               System.out.print(ex.getMessage());
               turnOf(num);
           }
       }
   
       private boolean check() {
           for(int i=0; i<3; i++) {
               if(field[i][0] == 0) continue;
               if(field[i][0] == field[i][1] && field[i][1] == field[i][2]) {
                   System.out.println("mr./ms. " + chars[field[i][0]] + " wins!" );
                   return false;
               }
           }   
           for(int i=0; i<3; i++) {
               if(field[0][i] == 0) continue;
               if(field[0][i] == field[1][i] && field[1][i] == field[2][i]) {
                   System.out.println("mr./ms. " + chars[field[0][i]] + " wins!");
                   return false;
               }
           }
           if(field[0][0] != 0 && field[0][0] == field[1][1] && field[1][1] == field[2][2]) {
               System.out.println("mr./ms. " + chars[field[0][0]] + " wins!");
               return false;
           }
           if(field[0][2] != 0 && field[0][2] == field[1][1] && field[1][1] == field[2][0]) {
               System.out.println("mr./ms. " + chars[field[0][2]] + " wins!");
               return false;
           }
           boolean isEnd = true;
           for(int i=0; i<3; i++) {
               for(int j=0; j<3; j++) {
                   if(field[i][j] == 0) {
                       isEnd = false;
                       break;
                   }
               }
           }
           if(isEnd) {
               System.out.println("draw...");
               return false;
           } else return true;
       }
   }

宿題スレPart67 >>489への回答 自動販売機

たぶんバグ結構あるけど、それでも良ければどうぞ。

// P67_489.java
import java.util.*;

public class P67_489 {
    public static void main(String[] args) {
        VendingMachine machine = new VendingMachine(4, 3, 2, 1);
        while(true) {
            System.out.print("何をしますか? 1: ジュースの補充、2: ジュースの販売 > ");
            Scanner scanner = new Scanner(System.in);
            int id = scanner.nextInt();
            switch(id) {
                case 1:
                    machine.restock();
                    break;
                case 2:   
                    machine.cell();
                    break; 
            }
        }
    }    
}
// VendingMachine.java
import java.util.*;
public class VendingMachine {
    private int ten;
    private int fifty;
    private int hundred; 
    private int fivehundred;

    private int money;

    private Juice apple;
    private Juice orange;
    private Juice coke;
    private Juice[] juices;

    public VendingMachine(int ten, int fifty, int hundred, int fivehundred) {
        this.ten = ten;
        this.fifty = fifty;
        this.hundred = hundred;
        this.fivehundred = fivehundred;        

        this.apple = new Juice(80, "リンゴジュース", 0);
        this.orange = new Juice(120, "オレンジジュース", 0);
        this.coke = new Juice(150, "コーラ", 0);

        this.juices = new Juice[] {apple, orange, coke};
    }    

    public void restock() {
        System.out.print("何を補充しますか? 1: リンゴ、2: オレンジ、3: コーラ > ");
        Scanner scanner = new Scanner(System.in);
        int id = scanner.nextInt();
        System.out.print("何個補充しますか? > ");
        int count = scanner.nextInt();
        Juice juice = null;
        switch(id) {
            case 1:
                juice = apple;
                break;
            case 2:
                juice = orange;
                break;
            case 3:    
                juice = coke;
                break;
        }
        juice.addStock(count);
        System.out.println(juice.getName() + "は" + juice.getStock() + "コになりました。");
    }

    public void cell() {
label :while(true) {
           System.out.print("お金を入れてください。1: \\10、2: \\50、3: \\100、4: \\500 5: ジュースを買う > ");
           Scanner scanner = new Scanner(System.in);
           int id = scanner.nextInt();
           switch(id) {
               case 1:
                   money += 10;
                   ten++;
                   printMoney();
                   break;
               case 2:
                   money += 50;
                   fifty++;
                   printMoney();
                   break;
               case 3:
                   money += 100;
                   hundred++;
                   printMoney();
                   break;
               case 4:
                   money += 500;
                   fivehundred++;
                   printMoney();
                   break;
               case 5:    
                   Juice juice = selectJuice();
                   if(juice != null) {
                       if(!checkMoney(juice)) {
                           System.out.println("お金が足りません。");
                           break label;
                       }
                       String message = checkChange(juice);
                       if(message == null || message.length() == 0) {
                           System.out.println("お釣りが足りません。");    
                           break label;
                       } else {
                        System.out.println(message);
                        juice.removeStock();
                       }
                   }
                   break label;
           } 
       }
    }

    private boolean checkMoney(Juice juice) {
        return money >= juice.getPrice(); 
    }

    private String checkChange(Juice juice) {
        StringBuilder builder = new StringBuilder();
        int change = money - juice.getPrice();
        if(change == 0) return "お釣りはありません";
        builder.append("お釣り:");
        if(fivehundred * 500 >= change) {
            if(change / 500 != 0) {
                builder.append("500円を" + change / 500 + "枚");
                change -= (change / 500) * 500;
            }
        }
        if(hundred * 100 >= change) {
            if(change / 100 !=0) {
                builder.append("100円を" + change / 100 + "枚");    
                change -= (change / 100) * 100;
            }
        }
        if(fifty * 50 >= change) {
            if(change / 50 != 0) {
                builder.append("50円を" + change / 50 + "枚");    
                change -= (change / 50) * 50;
            }
        }
        if(ten * 10 >= change) {
            if(change / 10 != 0) {
                builder.append("10円を" + change / 10 + "枚");    
                change -= (change / 10) * 10;
            }
        }
        if(change != 0) {
            return null;    
        }
        return builder.toString();

    }

    private Juice selectJuice() {
        System.out.print("何を買いますか? 1: リンゴ、2: オレンジ、3: コーラ > ");
        Scanner scanner = new Scanner(System.in);
        int id = scanner.nextInt();
        Juice juice = null;
        switch(id) {
            case 1:
                juice = apple;
                break;
            case 2:
                juice = orange;
                break;
            case 3:
                juice = coke;
                break;
        }   
        if(!juice.checkStock()) {
            System.out.println("在庫がありません。");    
            return null;
        }
        else return juice;
    }

    private void printMoney() {
        System.out.println("現在" + money + "円です。");
    }
}
// Juice.java
public class Juice {
    
    private int price;
    private String name;
    private int stock;
    
    public Juice(int price, String name, int stock) {
        this.price = price;
        this.name = name;
        this.stock = stock;
    }    

    public void addStock(int count) {
        this.stock += count;    
    }

    public void removeStock() {
        this.stock--;    
    }

    public boolean checkStock() {
        return this.stock > 0;    
    }

    public int getPrice() { return price; }
    public String getName() { return name; }
    public int getStock() { return stock; }
}
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

今日の20件

人気の30件

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