【初心者】Java の宿題ここで答えます 5.0【歓迎】
■ このスレッドは過去ログ倉庫に格納されています
0001デフォルトの名無しさん
05/02/02 22:19:281. 問題文は自己省略せずに、直接全部貼り付けてください。
宿題&課題をそのまま丸投げするのが、一番好ましい提示法です。
2. 数学問題は何々法でせよだけでなく、その解を出す為の数式を
具体的に詳細に説明してください。
3. 宿題&課題とその回答プログラムに対する質問はOKですが、
それ以外の質問はここではしないでください。
4. JavaScriptなど、他言語の課題はやめてください。
5. もし自分の提示課題への回答プログラムが返って来たら、
動いた動かなかった位の返レスをお願いします。
throws
コードはwikiに貼り付けてはいけません。
512kエラーなどなかったことにします。
【前スレ】
【好調】Java の宿題ここで答えます【三巡目】
http://pc5.2ch.net/test/read.cgi/tech/1100565043/
【関連サイト】
2ch Java初心者質問スレ Wiki
0002デフォルトの名無しさん
05/02/02 22:20:352ch Java初心者質問スレ Wiki
http://www.wikiroom.com/java/
..
0003デフォルトの名無しさん
05/02/02 22:26:510004デフォルトの名無しさん
05/02/02 22:30:10Stringをchar[]?
String[]をchar[]?
String[]をchar[][]?
0005デフォルトの名無しさん
05/02/02 22:33:040006デフォルトの名無しさん
05/02/02 22:36:28StringBufferでつなげてからtoCharArray()すれば?
0007デフォルトの名無しさん
05/02/02 22:39:56String str[] = {…};
char array[];
StringBuffer sb = new StringBuffer(1000);
for(int i = 0; i < str.length;i++)
sb.append(str[i]);
array = sb.toString().toCharArray();
0008デフォルトの名無しさん
05/02/02 22:40:590009デフォルトの名無しさん
05/02/02 22:50:050010デフォルトの名無しさん
05/02/02 23:00:30なんで5.0なんだよ…。
0011デフォルトの名無しさん
05/02/02 23:21:060012デフォルトの名無しさん
05/02/02 23:31:45いくつならいいんだー
0013デフォルトの名無しさん
05/02/02 23:43:20カット、コピー、ペーストまではできたのですが、以下が手も足もでませんでした。
「ctrl-a」を「行頭に移動」 に割り当てる。
「ctrl-space」を「マーク設定」 に割り当てる。
マーク設定後はキャレットが移動すると、
その設定したマークから現在のキャレットまでが選択される。
キャレットがらみのアクションをどうかけばよいかサッパリわからないのです。
どなたかお願い致します。。
0014デフォルトの名無しさん
05/02/02 23:47:02お願いだから質問は質問スレでしてよ。
0015デフォルトの名無しさん
05/02/02 23:47:530016デフォルトの名無しさん
05/02/03 00:09:57登場してからまだ半年も経っていないのにJava5の宿題がもう沢山出るほどになったのか?
0017デフォルトの名無しさん
05/02/03 00:14:04質問スレでしたのですが、みんなわからないのかスルーされっぱなしだったので・・
両方みているかぎり、こちらのほうが親切でレベル高い人が多そうに思えたので。
間違いでしたらすみません。
またほかのところで聞いてきます。
0020デフォルトの名無しさん
05/02/03 06:54:06親切に見えるのは問題文が明確になってるから答えやすいだけ。
答える人間はたぶんどっちのスレも見てるからレベルは対して変わらんと思う。
00211/2
05/02/03 10:33:30import java.awt.*;
import java.awt.event.*;
import javax.swing.border.*;
import javax.swing.text.*;
import java.io.*;
public class MyEditor extends JFrame{
Container myContainer;
JTextPane myTextPane;
public static void main(String[] args){
MyEditor myApp = new MyEditor( "( New File )" );
myApp.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myApp.setVisible(true);
}
00222/2
05/02/03 10:34:51super( title );
setBounds( 10, 10, 800, 500 );
myContainer = this.getContentPane();
myContainer.setLayout(new BorderLayout());
myTextPane = new JTextPane();
InputMap inputMap = myTextPane.getInputMap( JComponent.WHEN_IN_FOCUSED_WINDOW );
ActionMap actionMap = myTextPane.getActionMap();
KeyStroke moveLineStartKey = KeyStroke.getKeyStroke( "ctrl A" );
inputMap.put( cutKey, moveLineStartAction );
actionMap.put( moveLineStartAction, moveLineStartAction );
}
class MoveLineStartAction extends AbstractAction{
MoveLineStartAction( String text ){ super(text); }
public void actionPerformed( ActionEvent e ){
????
}
}
}
002317
05/02/03 10:40:03ソースの最後の方の、????の部分にCaretクラスのmoveDotというメソッドで、
改行にマッチするまでmoveDot(-1)を繰り返すというようにしたいのですが、
myTextPane.moveDot(-1)はダメですよね。
自分は継承とかアクションとかがそもそもあまりよく分かっていないのだと思います。
C言語になれていていつでもどこでも関数使いたいんですが・・。
もしよろしければ作ってみてください。
スレ汚しすいませんでした。
002423
05/02/03 19:19:290025デフォルトの名無しさん
05/02/03 19:42:46上記の十人のテストの成績をwhieを用いず、二通りの方法を考え、それぞれ成績の良いものから順に並び替えて表示させよ。
0026デフォルトの名無しさん
05/02/03 20:45:070027デフォルトの名無しさん
05/02/03 21:31:090028デフォルトの名無しさん
05/02/04 01:34:59public class TestSort {
public static void main(String[] args) {
int[] points = { 62,75,84,42,93,88,69,79,69,72 };
for (int i = 100; i >= 0; i--) {
for (int j = 0; j < points.length; j++) {
if (i == points[j]) {
System.out.println(points[j]);
}
}
}
}
}
002928
05/02/04 01:35:560030デフォルトの名無しさん
05/02/04 02:40:58>>927
(音楽サーチ)
http://www.wikiroom.com/java/?%A5%BD%A1%BC%A5%B9%C5%BD%C9%D5%A4%B1
に回答例を貼っときました。
半角空白、全角空白で区切った複数キーワードに対応してます。
検索&再生できるフォーマットはMIDIだけです・・・
アクセスに時間がかかるサイトなどでは、アクセス中止ボタンを押すと
アクセスを中断できます。
真ん中のテキストエリアの情報をよく見て操作してください。
取り合えず動作例としては、「クラシック音楽の部屋」で検索して
みてください。
0031デフォルトの名無しさん
05/02/04 03:03:33題材として、一行掲示板(ログ付きのチャットと読み替え可)を作成する。
クライアントの認証機能を付ける
サーバは書き込まれた内容を管理する
以上が必須項目です。
これだけしか制限はないのですが流れは、
ログイン(ここで認証?)
書き込みかログの読み込みの選択
・書き込み
・読み込み
ログアウト
のような感じだと思います。
簡単なもので構わないと思うのですが、
Java未経験なので何をしたら良いのか見当がつきません。
どなたか作って頂けませんでしょうか・・・
どうかよろしくお願いします。
003231
05/02/04 03:09:01土曜日の夜までにお願いします
0033デフォルトの名無しさん
05/02/04 07:16:54それホントに宿題なの?Java未経験でそんな宿題なんて・・・
0034デフォルトの名無しさん
05/02/04 07:49:57サーブレットじゃなくてJavaアプリだよね
0035デフォルトの名無しさん
05/02/04 07:58:060036デフォルトの名無しさん
05/02/04 11:36:57003731
05/02/04 16:06:00本当は言語は自由なんですが、途中までJavaでやってみたんです。
サーバとクライアントを繋げるのはネットで見つけたんですけど、
その先がわからなくて・・・
過去ログにあった、チャットを使うことってできますか?
>>34
プロトコルがいまいち分からないんですけど、
レポートにアルゴリズムとかやり取りを書けば良いみたいです。
>>35
出たのは結構前なんです・・・
0038デフォルトの名無しさん
05/02/04 17:59:14>出たのは結構前なんです・・・
便秘ですか?
0039デフォルトの名無しさん
05/02/04 23:53:25難しくて解けません
0040デフォルトの名無しさん
05/02/05 02:34:10http://www.geocities.co.jp/CollegeLife-Labo/4695/java/kadai16/sample.html
0041>>31 その1
05/02/05 03:15:49import java.util.*;
import java.util.regex.*;
import java.net.*;
import java.nio.*;
import java.nio.channels.*;
public class HW76 implements HtmlText {
private static final String HOST = "http://localhost";
private static final String PORT = ":80/";
private static final Map MEMBER = new TreeMap() {
{
put("田中", "tanaka");
put("鈴木", "suzuki");
put("佐藤", "satou");
put("高橋", "takahashi");
put("山田", "yamada");
}
};
private static Map partic = Collections.synchronizedMap(new TreeMap());
private static List chatLog = new ArrayList();
public static void main(String[] args) {
Selector sel;
try {
sel = Selector.open();
ServerSocketChannel sv = ServerSocketChannel.open();
sv.configureBlocking(false);
sv.socket().bind(new InetSocketAddress(80));
sv.register(sel, SelectionKey.OP_ACCEPT);
sv = ServerSocketChannel.open();
sv.configureBlocking(false);
sv.socket().bind(new InetSocketAddress(90));
sv.register(sel, SelectionKey.OP_ACCEPT, new Object());
0042>>31 その2
05/02/05 03:16:31System.out.println("サーバーバインドエラー");
return;
}
loop: while (!sel.keys().isEmpty()) {
try {
if (sel.selectNow() == 0)
continue;
} catch (Exception e1) {
continue;
}
Iterator it = sel.selectedKeys().iterator();
while (it.hasNext()) {
SelectionKey key = (SelectionKey) it.next();
Channel ch = key.channel();
if (ch instanceof ServerSocketChannel) {
if (key.attachment() != null)
break loop;
try {
ServerSocketChannel sc = (ServerSocketChannel) ch;
SocketChannel cc = sc.accept();
cc.configureBlocking(false);
cc.register(sel, SelectionKey.OP_READ);
} catch (Exception e) {
}
} else {
SocketChannel cc = (SocketChannel) ch;
if (key.readyOps() == SelectionKey.OP_READ)
processRead(key, cc);
else
processWrite(key, cc);
}
0043>>31 その3
05/02/05 03:17:42}
}
Iterator it = sel.keys().iterator();
while (it.hasNext()) {
SelectionKey key = (SelectionKey) it.next();
try {
key.channel().close();
} catch (IOException e) { }
}
try {
sel.close();
} catch (IOException e) { }
System.out.println("サーバー終了");
}
private static void processRead(SelectionKey key, SocketChannel cc) {
try {
ByteBuffer bb = (ByteBuffer) key.attachment();
if (bb == null)
bb = ByteBuffer.allocate(1000);
if (cc.read(bb) != -1 && bb.remaining() == 0)
return;
block: {
ByteBuffer value = ByteBuffer.wrap(new byte[] { 0x0d, 0x0a, 0x0d, 0x0a });
byte[] array = bb.array();
for (int i = 0; i + 4 < array.length; i++) {
if (value.equals(ByteBuffer.wrap(array, i, 4)))
break block;
}
return;
}
0044>>31 その4
05/02/05 03:18:22key.attach(buf);
key.interestOps(SelectionKey.OP_WRITE);
} catch (Exception e3) {
}
}
private static void processWrite(SelectionKey key, SocketChannel cc) {
try {
ByteBuffer bb = (ByteBuffer) key.attachment();
try {
cc.write(bb);
} catch (Exception e) {
}
if (bb.remaining() == 0) {
try {
cc.close();
} catch (IOException e3) {
}
key.cancel();
}
} catch (Exception e) {
}
}
private static ByteBuffer controlAccess(ByteBuffer bb) throws Exception {
DataInputStream in = new DataInputStream(new ByteArrayInputStream(bb.array()));
String line = in.readLine();
String[] token = line.split(" ");
String path = token[1];
String id = "", enter = "", leave = "", text = "";
Matcher mat = Pattern.compile("^/(\\w+)").matcher(path);
0045>>31 その5
05/02/05 03:19:04id = mat.group(1);
mat = Pattern.compile("enter=([^\\&]+)").matcher(path);
if (mat.find())
enter = mat.group(1);
mat = Pattern.compile("leave=([^\\&]+)").matcher(path);
if (mat.find())
leave = mat.group(1);
mat = Pattern.compile("text=([^\\&]+)").matcher(path);
if (mat.find())
text = mat.group(1);
boolean flag = false;
String auth = "";
while ((line = in.readLine()).length() > 0) {
token = line.split(":");
if (token[0].trim().equalsIgnoreCase("Authorization"))
auth = token[1].trim();
}
StringBuffer head = new StringBuffer(), body = new StringBuffer();
String host = HOST + PORT, name = "";
if (id.length() > 0 && partic.containsKey(id)) {
name = (String) partic.get(id);
if (text.length() > 0) {
addElementToChatLog(name, text);
head.append("HTTP/1.1 303 See Other\r\n");
head.append("Location: " + host + id + "\r\n\r\n");
} else if (leave.length() > 0){
partic.remove(id);
addElementToChatLog(name + "さんが退席しました");
head.append("HTTP/1.1 303 See Other\r\n");
head.append("Location: " + host + "\r\n\r\n");
} else {
0046>>31 その6
05/02/05 03:19:49head.append("HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n");
body.append(TITLE);
body.append(FORM);
generateText(body);
flag = true;
}
} else {
if (enter.length() > 0) {
if (auth.length() > 0 && (name = authorize(auth)) != null
&& !partic.containsValue(name)) {
synchronized (HW76.class) {
id = String.valueOf(System.currentTimeMillis());
}
partic.put(id, name);
addElementToChatLog(name + "さんが入室しました");
head.append("HTTP/1.1 303 See Other\r\n");
head.append("Location: " + host + id + "\r\n\r\n");
} else {
head.append("HTTP/1.1 401 Unauthorized\r\n");
head.append("WWW-Authenticate: Basic realm=\"chat\"\r\n\r\n");
}
} else {
head.append("HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n");
body.append(TITLE);
body.append(ENTER);
generateText(body);
flag = true;
}
}
0047>>31 その7
05/02/05 03:20:32if (flag) {
body.append(FOOT);
bodytxt = body.toString().replaceAll("#host#", host).replaceAll("#name#", name);
byte[] bodyB = bodytxt.getBytes("Shift_JIS");
head.append("Content-Length: " + bodyB.length + "\r\n\r\n");
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
out.write(head.toString().getBytes("Shift_JIS"));
out.write(bodytxt.getBytes("Shift_JIS"));
return ByteBuffer.wrap(out.toByteArray());
}
private static void generateText(StringBuffer body) {
List view = getChatLogView();
for (int i = view.size() - 1, c = 0; i >= 0 && c < 20; i--, c++) {
String[] dat = (String[]) view.get(i);
String text = TEXT.replaceAll("#name#", dat[0]).replaceAll("#text#", dat[1]);
body.append(text);
}
}
private static String authorize(String auth) {
String base64 = auth.split(" ")[1].trim();
ByteArrayOutputStream bs = new ByteArrayOutputStream();
int pos = 0;
byte buf = 0;
for (int i = 0; i < base64.length(); i++) {
char c = base64.charAt(i);
0048>>31 その8
05/02/05 03:21:38c = (char) (c - 'A' + 0 << 2);
} else if (c >= 'a' && c <= 'z') {
c = (char) (c - 'a' + 26 << 2);
} else if (c >= '0' && c <= '9') {
c = (char) (c - '0' + 52 << 2);
} else if (c == '+') {
c = (char) (c - '+' + 62 << 2);
} else if (c == '-') {
c = (char) (c - '-' + 63 << 2);
} else {
bs.write(buf);
break;
}
buf |= (byte) (c >>> pos);
if (pos + 6 >= 8) {
bs.write(buf);
buf = (byte) (c << (8 - pos));
}
pos = pos + 6 & 0x07;
}
try {
String dec = new String(bs.toByteArray(), "Shift_JIS");
String name = dec.split(":")[0].trim();
String pass = dec.split(":")[1].trim();
if (MEMBER.get(name).equals(pass)) return name;
else return null;
} catch (Exception e) {
return null;
}
}
0049>>31 その9
05/02/05 03:22:19synchronized (chatLog) {
return Collections.unmodifiableList(chatLog);
}
}
private static void addElementToChatLog(String name, String text) {
Matcher mat = Pattern.compile("%([\\dA-F]{2})|\\w+").matcher(text);
StringBuffer sb = new StringBuffer();
ByteArrayOutputStream bt = new ByteArrayOutputStream();
while (mat.find()) {
if (mat.group().matches("\\w+")) {
try {
sb.append(new String(bt.toByteArray(), "Shift_JIS"));
bt.reset();
} catch (UnsupportedEncodingException e) {
}
sb.append(mat.group());
} else {
bt.write(Integer.parseInt(mat.group(1), 16));
}
}
try {
sb.append(new String(bt.toByteArray(), "Shift_JIS"));
} catch (UnsupportedEncodingException e) {
}
synchronized (chatLog) {
chatLog.add(new String[] { name, sb.toString() });
}
}
0050>>31 その10
05/02/05 03:22:54synchronized (chatLog) {
chatLog.add(new String[] { "情報", text });
}
}
}
interface HtmlText {
String HEAD = "<html><head><meta http-equiv=content-type content=text/html; charset=Shift_JIS>"
+ "<meta http-equiv=content-style-type content=text/css><meta http-equiv=pragma content=no-cache>"
+ "</head><body>";
String TITLE = "<div style=\"text-align: center; font: bold 16px monospace; border: solid 2px rgb(0,0,160);"
+ "background-color: rgb(200,200,255); margin: 0% 5%\">チャットシステム</div>";
String ENTER = "<center><form action=#host# method=GET><input type=submit name=enter value=参加する></form></center>";
String FORM = "<br><form action=#host# method=GET style=\"margin: 0% 5%; border: dotted 2px rgb(160,120,200);"
+ "padding: 8px 0px; text-align: center; white-space: nowrap; background-color: rgb(250,245,255);\">"
+ "<input type=submit name=post value=送信> #name#さま:<input type=text name=text size=100 maxlength=100>"
+ "<input type=submit name=leave value=退席></form><br>";
String TEXT = "<div style=\"text-align: left; font: 16px monospace; border: dashed 1px rgb(200,200,255);"
+ "background-color: rgb(250,250,255); margin: 0% 5%; padding: 4px;\">#name#:#text#</div>";
String FOOT = "</body></html>";
}
0051デフォルトの名無しさん
05/02/05 03:28:39全部コピペしてコンパイル。
実行するとポート80にチャットサーバーがバインドされます。
インターネットエクスプローラなどのブラウザで、http://localhost
にアクセスするとチャット画面がでます。
ポート90にアクセスするとサーバーが終了します。(例:http://localhost:90)
名前&パスは
名前 パスワード
田中 tanaka
鈴木 suzuki
佐藤 satou
高橋 takahashi
山田 yamada
です
0052>>23 その1
05/02/05 03:43:51import javax.swing.text.*;
import java.awt.event.*;
public class HW75 {
public static void main(String[] args) {
final JTextArea ta = new JTextArea();
final InputMap oldmap = ta.getInputMap();
final InputMap newmap = new InputMap() {
public String toString() {
return "myMap";
}
};
newmap.put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0), "selection-forward");
newmap.put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0), "selection-backword");
newmap.put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0), "selection-up");
newmap.put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0), "selection-down");
newmap.setParent(ta.getInputMap());
oldmap.put(KeyStroke.getKeyStroke(KeyEvent.VK_A, InputEvent.CTRL_DOWN_MASK),
"linehead");
oldmap.put(KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, InputEvent.CTRL_DOWN_MASK),
"mark-switch");
0053>>23 その2
05/02/05 03:44:28amap.put("linehead", new AbstractAction() {
public void actionPerformed(ActionEvent e) {
try {
int pos = ta.getCaretPosition();
int lineno = ta.getLineOfOffset(pos);
ta.setCaretPosition(ta.getLineStartOffset(lineno));
} catch (BadLocationException e1) {
}
}
});
amap.put("mark-switch", new AbstractAction() {
public void actionPerformed(ActionEvent e) {
if (ta.getInputMap().toString().equals("myMap"))
ta.setInputMap(JComponent.WHEN_FOCUSED, oldmap);
else
ta.setInputMap(JComponent.WHEN_FOCUSED, newmap);
}
});
JFrame frame = new JFrame();
JScrollPane scroll = new JScrollPane(ta);
frame.getContentPane().add(scroll);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(640, 480);
frame.setVisible(true);
}
}
005431
05/02/05 04:01:15どうもありがとうございます。
コンパイルしてみたのですが、
HW76.java:121: 警告: java.io.DataInputStream の readLine() は推奨されません。
String line = in.readLine();
^
HW76.java:139: 警告: java.io.DataInputStream の readLine() は推奨されません。
while ((line = in.readLine()).length() > 0) {
とでました。どうしたら良いですか?
あと、これはクライアントのプログラムを作ることはできないんでしょうか?
0055デフォルトの名無しさん
05/02/05 07:52:070056デフォルトの名無しさん
05/02/05 12:08:02警告ですので、実行上は何も問題ありません。そのまま実行できます。
プログラムを簡単に作る為に、あえて非推奨メソッドを用いました。
通信時の文字セットがlatin限定の時は、readLine()は何も問題ありません。
自分のレベルでは、DataInputStream#readLine()はソケット通信の時に
非常に便利ですので、あえて使ってます。
クライアントプログラムはIEなどのブラウザです。IEでアクセス
してください。
0057デフォルトの名無しさん
05/02/05 12:33:59スレ立てどうもです。
005831
05/02/05 16:47:15実行できました。チャットも動きました
どうもありがとうございます。
0059デフォルトの名無しさん
05/02/05 17:24:300060デフォルトの名無しさん
05/02/05 17:27:29006159
05/02/05 17:34:430062デフォルトの名無しさん
05/02/05 17:42:140063デフォルトの名無しさん
05/02/05 18:42:04テストの結果を入力して
70点以上なら「合格」
それ以外なら「不合格」
というのはどのように打ちこめばいいのでしょうか?
よろしくお願いしますm(_ _)m
0064デフォルトの名無しさん
05/02/05 18:47:490065デフォルトの名無しさん
05/02/05 18:50:240066デフォルトの名無しさん
05/02/05 18:53:28006763
05/02/05 20:08:280068デフォルトの名無しさん
05/02/05 20:22:15質問は質問スレへ。
006963
05/02/05 20:48:39ああいう宿題なんです。
途中までやったのここに書こうとしたら串がなんとかでできないし・・・。
いまは携帯からですが自力でやってみます(´・ω・`)
007068
05/02/05 20:52:30そ。んじゃ。
// Seventy.java
import java.io.*;
public class Seventy {
public static void main(String[] args) throws IOException {
System.out.print( "点数を入力してください > " );
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = br.readLine();
int score = Integer.parseInt(line);
if( score >= 70 ) System.out.println( "合格" );
else System.out.println( "不合格" );
}
}
007163
05/02/05 21:53:21今からバイトなので帰ってから試してみます!
自分でやってたのと結構ちがってますねorz
0072デフォルトの名無しさん
05/02/06 00:43:48なにか良いアイデアがあったら助かります。
0074デフォルトの名無しさん
05/02/06 07:34:45ってか自分自身のIPアドレス&ホスト名を取得したいと思ってIPアドレスを
取得するのに↓こんな量になっちゃいました。もっと簡単な方法あるでしょうか?
(この質問をすると「127.0.0.1とlocalhost」と表示されちゃうプログラムを答える人が多い…)
//////////////////////
NetworkInterface ni = null;
InetAddress ipa = null;
Enumeration enuIfs = NetworkInterface.getNetworkInterfaces();
while(enuIfs.hasMoreElements()){
ni = (NetworkInterface)enuIfs.nextElement();//NetworkInterfaceに対する処理。
}
Enumeration enuAddrs = ni.getInetAddresses();
while(enuAddrs.hasMoreElements()){
ipa = (InetAddress)enuAddrs.nextElement();//InetAddressに対する処理。
}
String ipad = ipa.toString().substring(1);
///////////////////////
ってことでString型ipadにIPアドレス(127.0.0.1じゃないよ)が格納されています。
これをホスト名に変換したいんですが…
0075デフォルトの名無しさん
05/02/06 07:54:590076デフォルトの名無しさん
05/02/06 15:03:42String host = ipad.getHostName();
としませう
007774
05/02/06 15:19:29あっ、そうするとプロバイダのホスト名じゃなく、
ローカルPC名が表示されちゃうんですよ…
なぜなんでしょうね?
ちなみに@niftyなので〜〜なんたらかんたら〜.ppp.infoweb.ne.jp
みたいに表示されるようにしたいんです。
0078デフォルトの名無しさん
05/02/06 15:26:43String host = ipad.getCanonicalHostName()
としませう
007977
05/02/06 19:56:28それでもやはりPC名が出てします…
0080デフォルトの名無しさん
05/02/06 20:18:500081デフォルトの名無しさん
05/02/06 21:04:02ダジャレ
0082デフォルトの名無しさん
05/02/06 23:54:410083oops
05/02/07 00:45:19さらにVegetableクラスから3つのサブクラス、Carrot,Pumpkin,PotatoをFruitクラスから4つのサブクラスApple,Banana,
Orange,Strawberryを作成し、display()メソッドではその種類を日本語で表示するようにしなさい(例:にんじん、りんごなど)
mainメソッドで、各サブクラスをインスタンス化しFood型に配列に格納しなさい。ループを用いてdisplay()メソッドを呼び出し
なさい。
だれかよろしくおねがいします
0084デフォルトの名無しさん
05/02/07 01:37:37Application Programming Interface
0085デフォルトの名無しさん
05/02/07 01:38:37Application Programming Interface
0086デフォルトの名無しさん
05/02/07 01:40:03abstract class Food{ abstract public void display();}
abstract class Vegetable extends Food{
protected String name;
public void display(){ System.out.println(name); } }
abstract class Fruit extends Food{
protected String name;
public void display(){ System.out.println(name); } }
class Carrot extends Vegetable{public Carrot(){ name = "にんじん"; }}
class Pumpkin extends Vegetable{ public Pumpkin(){ name = "かぼちゃ"; }}
class Potato extends Vegetable{ public Potato(){ name = "じゃがいも"; } }
class Apple extends Fruit{ public Apple(){ name = "りんご"; } }
class Banana extends Fruit{public Banana(){ name = "バナナ"; } }
class Orenge extends Fruit{public Orenge(){ name = "みかん"; } }
class Strawberry extends Fruit{public Strawberry(){ name = "いちご"; } }
public class FoodTest{
public static void main(String[] args){
Food[] foods = new Food[7];
foods[0] = new Carrot();
foods[1] = new Pumpkin();
foods[2] = new Potato();
foods[3] = new Apple();
foods[4] = new Banana();
foods[5] = new Orenge();
foods[6] = new Strawberry();
for(int i=0;i<foods.length;i++) foods[i].display();
}
}
0088デフォルトの名無しさん
05/02/08 16:25:16Write a program to allow a randomly placed remote-controlled robot (in a grid environment) to move to its home.
(The home is also randomly placed, and needs to be shown on the grid.)
The user will specify the robot moves.The robot can move horizontally or vertically but not diagonally to an adjacent cell.
It must pay $1.00 travel fee for every move it makes.
Calculate the total cost to go home.The program should not let the user drop the robot off the planet.
You can use keys such as “i” for up, “j” for left, “l” for right and “m” for down, or the arrow keys, or mouse clicks on a cell.
(The mouse clicks are harder to program.)
Update the world after each move to show the new location of the robot, relative to the home location.
The user can specify the size of the world (in terms of number of cells).
The world is a flat square (that is, it is an nXn matrix.) Using a GUI interface will earn a maximum of 110 points.
There is only one player at this time in this game.
The user can also reset a game or play a new game when the current game is over.
英文で失礼します。以下概略です。
ロボットをキーボードで操作してHOMEに帰すゲームです。
以下がゲームの必要事項です。
スタートボタンを押すとロボットとHOMEをランダムで格子状のステージに配置します。
HOMEはプレイヤーにはわからないようにします。
ロボットはキーボード操作でマスを上下左右に移動できます。(斜めはなし)
上=I, 下=M, 右=L, 左=Jのキー配置です。
ロボットが一マス動くごとに1ドルのコストがかかり、それを計算して最終的にトータルコストを表示します。
ロボットが一マス動くごとにステージをアップデートしてHOMEまでの距離を表示します。
ロボットがHOMEについた時点でゴールです。
ゴール後ウィンドウをポップアップさせてトータルのコストとリプレイするかしないかを表示します。
アプレットとgridLayoutを使って作ります。
以上です。
どなたかお願いいたします。
0089デフォルトの名無しさん
05/02/08 17:14:34交わりはNの1割くらいにする。
Nを変化させる。
ハッシュを用いる方法と最も早い整列(比較を用いる)を用いる方法の2通りを実現して、両者も比較する。
課題本文を丸写ししました。
どなたかプログラムだけでも教えて頂けないでしょうか?
お願いします。
009068
05/02/08 22:16:41// RobotApplet.java
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/*
* <applet code="RobotApplet.class" width="400" height="400"> </applet>
*/
public class RobotApplet extends Applet implements KeyListener {
public static final int SIZE_ROW = 5;
public static final int SIZE_COL = 5;
JPanel northPanel, southPanel;
JTextField messageField;
private int cost = 0;
int HOME_POS = 0;
int robot_pos = 0;
private JLabel[] labels = new JLabel[SIZE_ROW*SIZE_COL];
public void init() {
play();
}
private void play() {
cost = 0;
northPanel = new JPanel();
southPanel = new JPanel();
setLayout(new BorderLayout());
northPanel.setLayout(new GridLayout(SIZE_ROW, SIZE_COL));
for( int i=0; i<SIZE_ROW*SIZE_COL; i++ ) {
labels[i] = new JLabel();
labels[i].setFont(new Font(null, Font.PLAIN, 15));
labels[i].setBorder( BorderFactory.createMatteBorder(1, 1, 1, 1, Color.BLACK) );
northPanel.add(labels[i]);
009168
05/02/08 22:17:23つづき
}
robot_pos = (int)(Math.random()*SIZE_ROW*SIZE_COL);
putRobot( robot_pos );
HOME_POS = robot_pos;
do {
HOME_POS = (int)(Math.random()*SIZE_ROW*SIZE_COL);
putHome( HOME_POS );
} while( robot_pos == HOME_POS );
southPanel.add(messageField = new JTextField(10));
messageField.setEditable(false);
messageField.setText( "距離:" + calculateDistance() );
add(BorderLayout.CENTER, northPanel);
add(BorderLayout.SOUTH, southPanel);
addKeyListener(this);
}
private void putRobot(int i) {
labels[i].setText("p[-_-]q");
}
private void removeRobot(int i) {
labels[i].setText("");
}
private void putHome(int i) {
// labels[i].setText("H");
}
private int[] one2two(int i) {
if( i>SIZE_ROW*SIZE_COL-1 ) System.out.println( "ERROR at one2two()" );
return new int[]{ i/SIZE_COL, i%SIZE_COL, };
}
private int two2one(int[] is) {
int i = is[0]*SIZE_COL + is[1];
009268
05/02/08 22:17:53つづき
if( i>SIZE_ROW*SIZE_COL-1 ) System.out.println( "ERROR at two2one()" );
return i;
}
private int calculateDistance() {
int[] robot_pos__ = one2two(robot_pos);
int[] home_pos__ = one2two(HOME_POS);
return Math.abs(robot_pos__[0]-home_pos__[0]) + Math.abs(robot_pos__[1]-home_pos__[1]);
}
public void keyTyped(KeyEvent ke) {
removeRobot(robot_pos);
// 上
if(ke.getKeyChar() == 'i' || ke.getKeyChar() == 'I') {
robot_pos = (robot_pos - SIZE_COL < 0 ? robot_pos : robot_pos - SIZE_COL);
cost++;
// 下
} else if(ke.getKeyChar() == 'm' || ke.getKeyChar() == 'M') {
robot_pos = (robot_pos + SIZE_COL > SIZE_ROW*SIZE_COL-1 ? robot_pos : robot_pos + SIZE_COL);
cost++;
// 右
} else if(ke.getKeyChar() == 'l' || ke.getKeyChar() == 'L') {
robot_pos = ( one2two(robot_pos)[1]+1 > SIZE_COL-1 ? robot_pos : robot_pos+1 );
cost++;
// 左
} else if(ke.getKeyChar() == 'j' || ke.getKeyChar() == 'J') {
robot_pos = ( one2two(robot_pos)[1]-1 < 0 ? robot_pos : robot_pos-1 );
cost++;
}
putRobot(robot_pos);
int distance = calculateDistance();
messageField.setText( "距離:" + distance );
009368
05/02/08 22:19:08つづき
if( distance == 0 ) {
removeKeyListener(this);
final JDialog dialog = new JDialog( new JFrame(), "おめ", true );
dialog.setSize( 200, 100 );
dialog.setLayout(new BorderLayout());
JLabel messageLabel = new JLabel();
messageLabel.setText( "コスト:" + cost);
JButton continueButton = new JButton("続ける");
JButton cancelButton = new JButton("やめる");
continueButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
dialog.dispose();
play();
repaint();
}
});
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
dialog.dispose();
}
});
dialog.add(BorderLayout.CENTER, messageLabel);
JPanel p = new JPanel();
p.add(continueButton);
p.add(cancelButton);
dialog.add(BorderLayout.SOUTH, p);
dialog.setVisible(true);
}
}public void keyPressed(KeyEvent ke) {}public void keyReleased(KeyEvent ke) {}
}
009468
05/02/08 22:20:00009568
05/02/08 22:30:57あうあうあー。ちょいバグありました。
(1)
play()直後の
cost = 0;
は取ってください。
(2)
do...while内の
putHome(HOME_POS);
はwhile文の直後にしてください。
---
do {
HOME_POS = (int) (Math.random() * SIZE_ROW * SIZE_COL);
} while (robot_pos == HOME_POS);
putHome(HOME_POS);
---
つー感じで。
他にもバグあるだろーな。。。
0096デフォルトの名無しさん
05/02/09 00:09:38その問題文はどうも分かりません・・・・
009788
05/02/09 12:24:01遅くなりましたが、どうもありがとうございました。
これから確認してまた返事したいと思います。
009888
05/02/09 16:07:36NetBeans 3.6を使って書いたのですが、実行すると「アプレットが初期化されていません」
というメッセージが出てプレイできません。
010088
05/02/09 22:55:39申し訳ないです。
java.lang.NoClassDefFoundError: program1/robotApplet (wrong name: robotApplet)
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:620)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:124)
at sun.applet.AppletClassLoader.findClass(AppletClassLoader.java:162)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at sun.applet.AppletClassLoader.loadClass(AppletClassLoader.java:118)
at java.lang.ClassLoader.loadClass(ClassLoader.java:251)
at sun.applet.AppletClassLoader.loadCode(AppletClassLoader.java:577)
at sun.applet.AppletPanel.createApplet(AppletPanel.java:710)
at sun.applet.AppletPanel.runLoader(AppletPanel.java:639)
at sun.applet.AppletPanel.run(AppletPanel.java:319)
at java.lang.Thread.run(Thread.java:595)
■ このスレッドは過去ログ倉庫に格納されています