sample program

ちょっとしたプログラムを作成したので書いておく。

public class Reverse {
private String s;
private java.util.Stack stack = new java.util.Stack();
public Reverse(String s_) throws Exception {
if (s_.length() < 1 || 1000 < s_.length()) {
throw new Exception(“文字列長が不正です”);
}
s = s_;
}
public String execute() {
char[] cs = s.toCharArray();
for (int i=0 ; i<cs.length ; i++) {
stack.push(new Character(cs[i]));
}
StringBuffer sb = new StringBuffer();
while (!stack.empty()) {
Character c = (Character)stack.pop();
sb.append(c.charValue());
}
return new String(sb);
}
public static void main(String[] args) {
try {
String s = “0123456789”;
Reverse rev = new Reverse(s);
String rs = rev.execute();
System.out.println(“入力文字列:”+s);
System.out.println(“反転文字列:”+rs);
} catch(Exception e) {
System.out.println(“エラーが発生しました”);
}
}
}

 

import java.awt.Color;
import java.awt.Image;
import java.awt.Graphics;
import java.util.Iterator;
import java.util.Vector;
public class Cg extends javax.swing.JFrame {
interface Shape {
void draw(Graphics g);
}
class Circle implements Shape {
int x; int y; int r; Color c;
public Circle(int x_, int y_, int r_, Color c_) { x=x_; y=y_; r=r_; c=c_;}
public void draw(Graphics g) {
Color oc = g.getColor();
g.setColor(c);
g.fillOval(x-r, y-r, 2*r, 2*r);
g.setColor(oc);
}
}
class Square implements Shape {
int x; int y; int width; Color c;
public Square(int x_, int y_, int w_, Color c_) { x=x_; y=y_; width=w_; c=c_;}
public void draw(Graphics g) {
Color oc = g.getColor();
g.setColor(c);
g.fillRect(x, y, width, width);
g.setColor(Color.black);
g.drawRect(x, y, width, width);
g.setColor(oc);
}
}
private Vector shapes = new Vector();
private Graphics offscreen;
private Image image;
public Cg() {
shapes.add(new Square(0, 0, 320, Color.white));
shapes.add(new Square(120, 120, 80, Color.lightGray));
shapes.add(new Circle(80,80,80, Color.black));
shapes.add(new Square(160, 0, 80, Color.lightGray));
shapes.add(new Square(240, 0, 80, Color.lightGray));
shapes.add(new Square(240, 80, 80, Color.lightGray));
shapes.add(new Circle(240,240,80, Color.black));
shapes.add(new Square(0, 160, 80, Color.lightGray));
shapes.add(new Square(0, 240, 80, Color.lightGray));
shapes.add(new Square(80, 240, 80, Color.lightGray));
}
public void paint(Graphics g) {
update(g);
}
public void update(Graphics g) {
if (offscreen == null) {
image = createImage(321, 321);
offscreen = image.getGraphics();
return;
}
Iterator iterator = shapes.iterator();
while (iterator.hasNext()) {
Shape s = (Shape)iterator.next();
s.draw(offscreen);
}
g.drawImage(image, 10, 25, 321, 321, this);
}
public static void main(String[] args) {
Cg cg = new Cg();
cg.setSize(340, 360);
cg.setVisible(true);
cg.repaint();
}
}
同じカテゴリの記事: Java