Javaの基礎プログラム | 座標上の重なる長方形座標を求める

このQ&Aのポイント
  • Javaの基礎プログラムで、座標上の二つの長方形の重なり合う部分の座標を求めるプログラムです。
  • 結城浩さんの本に載っているプログラムで、X軸とY軸で座標を示し、重なり合う領域の座標を求めています。
  • プログラム内の長方形の座標は、順にa、b、c、d、eを表しており、それぞれの座標と重なり合いを出力しています。
回答を見る
  • ベストアンサー

Javaの基礎のプログラム

結城浩さんの本に載っていたプログラムです。 ですが、説明がわかりにくくていまいち処理がわからなかったので 質問させていただきました。 どうやら、X軸とY軸がありY軸は下に行けばいくほど数字が大きくなる。 X軸は右に行けばいくほど大きくなる。座標上にある、二つの長方形の重なりあう部分の座標を求めるプログラムのようです。(イメージとしては、下に添付してある画像のような感じになるようです。) 質問としては一つです。 プログラム中のこの部分なのですが、おそらく「長方形の座標を示している」行であると思います。 a = new Rectangle(0, 0, 20, 10); b = new Rectangle(5, 5, 20, 10); c = new Rectangle(20, 10, 20, 10); d = new Rectangle(-10, -20, 100, 200); e = new Rectangle(21, 11, 20, 10); その後の処理としては、aとb→c→d→eというようにそれぞれ比較していっているのもなんとなくわかります。 ですが、しっかり解説されていなかったので、この4つの数字がどのように座標を示しているのかよくわかりませんでした。 よろしくお願いします。 class Rectangle { final int INITIAL_WIDTH = 10; final int INITIAL_HEIGHT = 20; int width; int height; int x; int y; Rectangle() { width = INITIAL_WIDTH; height = INITIAL_HEIGHT; x = 0; y = 0; } Rectangle(int width, int height) { this.width = width; this.height = height; this.x = 0; this.y = 0; } Rectangle(int x, int y, int width, int height) { this.width = width; this.height = height; this.x = x; this.y = y; } void setLocation(int x, int y) { this.x = x; this.y = y; } void setSize(int width, int height) { this.width = width; this.height = height; } public String toString() { return "[" + x + ", " + y + ", " + width + ", " + height + "]"; } Rectangle intersect(Rectangle r) { int sx = Math.max(this.x, r.x); int sy = Math.max(this.y, r.y); int ex = Math.min(this.x + this.width, r.x + r.width); int ey = Math.min(this.y + this.height, r.y + r.height); int newwidth = ex - sx; int newheight = ey - sy; if (newwidth > 0 && newheight > 0) { return new Rectangle(sx, sy, newwidth, newheight); } else { return null; } } public static void main(String[] args) { Rectangle a, b, c, d, e; a = new Rectangle(0, 0, 20, 10); b = new Rectangle(5, 5, 20, 10); c = new Rectangle(20, 10, 20, 10); d = new Rectangle(-10, -20, 100, 200); e = new Rectangle(21, 11, 20, 10); System.out.println("a = " + a); System.out.println("b = " + b); System.out.println("c = " + c); System.out.println("d = " + d); System.out.println("e = " + e); System.out.println("a と a の重なり = " + a.intersect(a)); System.out.println("a と b の重なり = " + a.intersect(b)); System.out.println("a と c の重なり = " + a.intersect(c)); System.out.println("a と d の重なり = " + a.intersect(d)); System.out.println("a と e の重なり = " + a.intersect(e)); } }

  • Java
  • 回答数1
  • ありがとう数4

質問者が選んだベストアンサー

  • ベストアンサー
  • askaaska
  • ベストアンサー率35% (1455/4149)
回答No.1

a = new Rectangle(0, 0, 20, 10); は座標(0,0)を基点とした幅20高さ10の長方形。 b = new Rectangle(5, 5, 20, 10); は座標(5,5)を基点とした幅20高さ10の長方形。 てことよ。 メソッドintersectは 自分自身と、引数に渡された長方形の 重なり合っている部分の長方形の 基点と幅・高さを算出しているわ。 そしてtoStringで基点の座標と幅・高さを出力している。

rinnshan
質問者

お礼

回答ありがとうございます!! なるほど、そういう仕組みになっているんですね。 解決することができました^^

関連するQ&A

  • java

    次のコード中の括弧内で下に示す11通りの各コードを実行した場合の実行画面を正確に答えよ。 class A{ public void func1(){System.out.println("A1");} public void func2(){System.out.println("A2");} } class B extends A{ public void func1(){System.out.println("B");} } class C{ public int x=0, y=1; } class D extends C{ public int x=2; public void func1(int x){System.out.println(x);} public void func2(int x){System.out.println(this.x);} public void func3(int x){System.out.println(super.x);} public void func4(int x){System.out.println(this.y);} public void func5(int x){System.out.println(super.y);} } class E{ public void func1(int n){ try{ System.out.println("E1"); int[] ary=new int[n]; System.out.println("E2"); }catch(NegativeArraySizeException e){ System.out.println("E3"); }finally{ System.out.println("E4"); } } } (1) A a=new A(); a.func1(); (2) A a=new B(); a.func1(); (3) B b=new B(); b.func1(); (4) B b=new B(); b.func2(); (5) D d=new D(); d.func1(3); (6) D d=new D(); d.func2(3); (7) D d=new D(); d.func3(3); (8) D d=new D(); d.func4(3); (9) D d=new D(); d.func5(3); (10) E e=new E(); e.func1(5); (11) E e=new E(); e.func1(-2); (1) A1 (2)B (3)B (4) A2 (5) 3 (6) 2 (7) 0 (8) 1 (9) 1 (10) E1E2E4(11) E1E3E4 と答えになるんですがなぜこうなるのかわかりません。教えてください

    • ベストアンサー
    • Java
  • java 継承

    こんにちは。 javaの問題なのですが、問題文が理解できなかったので質問させていただきます。 問題文 Ex54で作成したRectangleクラスを継承するPlaceRectangleクラスを作成する Ex54 import java.io.*; class Rectangle{ private int width; private int height; public Rectangle(){ width=0; height=0; } public Rectangle(int w, int h){ width=w; height=h; } public int getArea(){ return width*height; } } class Ex54{ public static void main(String args[])throws IOException{ BufferedReader br = new BufferedReader (new InputStreamReader(System.in)); int num=0; while(num < 2){ System.out.print(">"); String wid = br.readLine(); System.out.print(">"); String hei = br.readLine(); int num1 = Integer.parseInt(wid); int num2 = Integer.parseInt(hei); Rectangle rectangle1 = new Rectangle(num1, num2); System.out.println("インスタンスr" + (num+1) + "の面積は" + rectangle1.getArea()); num++; } } } --------------------------------------------------------------- PlacedRectangleクラス 四角形の位置をx座標y座標で表す。 長方形の左端を示しx座標は右に大きくy軸は下に大きくなる。 ・次の三つのコンストラクタを持つ (1)引数なし (2)位置の引数付き (3)位置と大きさの引数付き いづれのコンストラクタも位置のセットはsetLocationメソッドを実行する 大きさのセットはスーパークラスのコンストラクタを呼ぶ (コンストラクタで値を設定しているのになぜ再設定(位置のセット、大きさのセット)する必要があるのか分かりません。) ・setLocationメソッドは位置をセットする mainメソッドから次の操作をする 1引数無しでPalacedRectangleのインスタンスaを作成 2引数12と34でPlacedRectangleのインスタンスbを作成 3引数31と41と59と26でPlacedRectangleのインスタンスcを作成 1、2、3ともそれぞれのインスタンスの位置と面積を表示する 実行例 インスタンスaの面積は1534 位置は(12,13)です。 UML図 PlacedRectangle ----------------- -x:int -y:int ----------------- +PlacedRectangle() +PlacedRectangle(x:int,y:int) +PlacedRectangle(x:int,y:int,width:int,height:int) +setLocation(x:int,y:int):void 「疑問点」 コンストラクタで値を設定しているのになぜ再設定(位置のセット、大きさのセット)する必要があるのか分かりません。 main文のwhile(num < 2){というところをスッキリさせたい(処理が2回しかないため)何かよい方法はないでしょうか? よろしくおねがいします。

    • ベストアンサー
    • Java
  • javaの課題が難しくて解けません。力を貸してください

    本日、プログラムの授業で課題が出されました。 解ける方がいましたら、回答を教えてください。 課題:これまでの演習で作成した Rectangle, Triangle, Circle, Trapezoidクラスを利用するクラス (メインクラス)を修正して, コマンドライン引数から図形の種類、入力値を指定できるようにしてみよ。 ※4つのクラスをpackageで1つにまとめる必要があるようです。 お手数かけますが、宜しくお願いします。 下記が演習で作成した4つのクラスになります。参考にしてください。 (Rectangleクラス) import java.io.*; class Rectangle { private int width; private int height; public Rectangle(int w, int h) { width = w; height = h; } public void setWidth(int w) { width = w; } public void setHeight(int h) { height = h; } public int getWidth() { return width; } public int getHeight() { return height; } public double calcArea() { return width * height; } public void show() { System.out.println("width=" + getWidth() + ", height= " + getHeight()); } } public class kadai1 { public static void main(String args[]) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.print("width= "); String str1 = br.readLine(); System.out.print("height= "); String str2 = br.readLine(); Rectangle r = new Rectangle(Integer.parseInt(atr1),Integer.parseInt(str2)); r.show(); System.out.println("面積 = " + r.calcArea()); } } (Triangleクラス) public double calcArea() { return width * height / 2.0; } (Circleクラス) public double calcArea() { return Math.PI * radius * radius; } public void show() { System.out.println("radius= " + getRadius()); } (Trapezoidクラス) public double calcArea() { return (upper + lower) * height / 2.0; } public void show() { System.out.println("upper= " + getUpper() + ", lower= " + getLower() + ", height= " + getHeight()); }

  • javaについての質問です。

    javaについての質問です。 public class MyTurtleFrame extends TurtleFrame { Turtle[] turtleList = new Turtle[10]; /*ここの箇所をArraylistをつかって書き換える*/ int numTurtles = 0;/*ここの箇所をArraylistをつかって書き換える*/ public MyTurtleFrame() { this(400, 400); } public MyTurtleFrame(int width, int height) { super(width, height); JMenu turtles = new JMenu("Tuttle", true); this.frame.getJMenuBar().add(turtles); JMenuItem add = new JMenuItem("Add"); JMenuItem del = new JMenuItem("Delete"); add.addActionListener(this); del.addActionListener(this); add.setActionCommand("addTurtle"); del.setActionCommand("delTurtle"); turtles.add(add); turtles.add(del); this.frame.setVisible(true); } public void actionPerformed(ActionEvent e) { super.actionPerformed(e); if (e.getActionCommand().equals("addTurtle")) { this.addTurtle(); } if (e.getActionCommand().equals("delTurtle")) { this.delTurtle(); } this.repaint(); } protected void addTurtle() { int x = (int) (Math.random() * this.frame.getContentPane().getWidth()); int y = (int) (Math.random() * this.frame.getContentPane().getHeight()); try{ turtleList[numTurtles]=new Turtle(x, y, 0); this.add(turtleList[numTurtles]); numTurtles++; System.out.println(numTurtles); }catch(Exception a){ System.out.println("例外が発生しました");} } protected void delTurtle(){ try{ this.remove(turtleList[numTurtles-1]); numTurtles--; }catch(Exception a){ System.out.println("例外が発生しました"); } } public static void main(String[] args) { MyTurtleFrame f=new MyTurtleFrame(); } } 文中のコメントが書いてある箇所をArraylistをつかって書き換えて,それに応じてaddTurtleとdelTurtleも適切に書き換える問題なのですが解決の糸口がどうしてもわかりません。 解答を導くヒントをご教授いただけるかたよろしくお願いします。

    • ベストアンサー
    • Java
  • javaで課題を出されています

    題名の通りなのですが、javaのプログラミングで課題を出されていて うまく書けません お題としては 1 if分と論理演算を使うこと。 2 forまたはwhileを使用すること 3 メソッドを使用すること。(main以外で) 4 配列を使用すること 以上なのですが、一応昔スロットプログラムを作っていたのでこれをベースに作ろうかなと考えています import java.io.*; public class Slot01{ public static void main(String[] args){ try{ //String line =reader.readLine(); BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); System.out.println("こんにちは!スロットゲームへようこそ!"); System.out.println("EnterKeyを押して当たりを出してくださいね!"); while(true){ //while文は処理を繰り返すためのものです。 // ▽これよりソースを打ち込んでください //try{ int x=(int)(Math.random()*9)+1; int y=(int)(Math.random()*9)+1; int z=(int)(Math.random()*9)+1; int[]kakuritu; int sum; System.out.print(x); System.out.print(y); System.out.print(z); System.out.println(""); String line =reader.readLine(); //System.out.println(""); if(x==7&&y==7&&z==7){ System.out.println("スーパー大当たり"); }else if(x==y&&y==z){ System.out.println("大当たり"); }else if(x==y||y==z||x==z){ System.out.println("小当たり"); }else{ System.out.println("外れ"); } }//while文の終わり }catch (IOException e){ System.out.println(e); }catch (NumberFormatException e){ System.out.println("正しい形式で表示してください。"); } } } このプログラムなのですが、1と2はこの中に入ってます。考えてみたのですが、このプログラムに当たり確率を表示させるプログラムなら3と4も満たせそうなのですが、いまいちソースが思いつきませんのでご教授お願いします。 文章おかしいところだらけで申し訳ありません。

    • ベストアンサー
    • Java
  • パッケージ化とコンパイルについて

    下記のプログラムにについての質問になります。 /*Rectangle.java*/ package com.shoeisha.shape; public class Rectangle { private int width; private int height; public Rectangle() { } public Rectangle(int width, int height) { this.width = width; this.height = height; } public int getArea(){ return width * height; } } /*Test.java*/ import com.shoeisha.shape.*; ^^(1) class Test { public static void main(String[] args) { Rectangle rc = new Rectangle(10, 15); System.out.println(rc.getArea()); } } (1)の箇所になりますが、com.shoeisha.shapeにあるクラス(Rectangle)を 利用し、プログラムを作成しようと思うのですが、Test.javaにてコンパイルエラーが生じてしまいます。 (1)の箇所をRectangleにするとコンパイルが通るようになり、「*」は使えないものかと思えてしまいます。 java.util.*;といった、既に用意されているものは普通に使えるのですが、自作でパッケージ化した物は 正規表現を使うことができないものなんでしょうか?? 何かの設定がされていないから、正規表現が使えないのではと思っておりますが、 それ以上がわかりませんでしたので、掲示板にて記載させていただきました。 以上、ご教授の程お願い致します。

    • ベストアンサー
    • Java
  • この2つのプログラムは全く同じものでしょうか?

    class Base{ protected int x; Base() { this.x=0;} Base(int x) {this.x=x;} void print(){ System.out.println("Base.x="+x);} } class Derived extends Base{ int x; Derived(int x1,int x2){ super(x1); this.x=x2;} void print(){ super.print(); System.out.println("Derived.x="+x);} } public class SuperTester{ public static void main(String[] args){ Base a =new Base(10); System.out.println("----a----"); a.print(); Derived b=new Derived(20,30); System.out.println("----b----"); b.print(); } } このプログラムと、 このプログラムのDerivedクラスのコンストラクタの部分を Derived(int x1,int x2){ super.x=x1; this.x=x2;} に変えたプログラムです。 かなりややこしいのですが、この2つのプログラムはソースは一部違いますが、 意味するものは全く同じでしょうか? ちなみにこの2つは実行結果は同じになります。 【実行結果】 ----a---- Base.x=10 ----b---- Base.x=20 Derived.x=30 つまり、Derivedクラスでint x;を書かず、 よろしくお願いします。

    • ベストアンサー
    • Java
  • 実行するにはどうすれば良いのでしょうか?

    まず、 class Car{ private String name; private int width; private int height; private int length; private double x; private double y; private double fuel; Car(String name,int width,int height,int length,double fuel){ this.name=name; this.width=width; this.height=height; this.length=length; this.fuel=fuel; x=y=0; } double getX() {return x;} double getY() {return y;} double getFuel() {return fuel;} void putSpec(){ System.out.println("名前:"+name); System.out.println("車幅:"+width+"mm"); System.out.println("車高:"+height+"mm"); System.out.println("車長:"+length+"mm"); } boolean move(double dx, double dy){ double dist = Math.sqrt(dx*dx+dy*dy); if(dist < fuel) return false; else { fuel -= dist; x += dx; y +=dy; return true; } } } のファイルをcar.javaと名前をつけて保存しました。 次に import java.util.Scanner; class CarTester2{ public static void main(String[] args){ Scanner stdIn = new Scanner(System.in); System.out.println("車のデータを入力せよ。"); System.out.println("名前は:"); String name = stdIn.next(); System.out.println("車幅は:"); int width = stdIn.nextInt(); System.out.println("高さは:"); int height =stdIn.nextInt(); System.out.println("長さは:"); int length =stdIn.nextInt(); System.out.println("ガソリン量は:"); double fuel= stdIn.nextDouble(); Car myCar = new Car(name,width,height,length,fuel); while(true){ System.out.println("現在地("+myCar.getX()+","+myCar.getY()+")・残り燃料"+myCar.getFuel()); System.out.print("移動しますか[0…No/1…Yes]:"); if(stdIn.nextInt()==0) break; System.out.print("X方向の移動距離:"); double dx = stdIn.nextDouble(); System.out.print("Y方向の移動距離:"); double dy = stdIn.nextDouble(); if(!myCar.move(dx,dy)) System.out.println("燃料が足りません!"); } } } のファイルをCarTester2.javaという名前で保存しました。 この2つのファイルは同一フォルダに入っています。 それで、 javac CarTester2.javaという風にコンパイルしても 「エラー4  変数myCarのシンボルが見つけられません」 といった感じにコンパイルエラーとなってしまいます。 何が原因なのでしょうか?

  • JAVAのComparableについて・・・

    compareto()を使って名前、身長、体重を「身長昇順」拡張for文でだしたいのですが・・・ (1)returnを使って何を返せばいいのか? (2)System.out.println()でなにをすればいいのか? (3)他の文で間違っているのか? この3点が分かりません。JAVAに詳しい方よろしくお願いします。。。 package class; public class NewClass { public static void main(String[] args) { NewClass2 A = new NewClass2("aaa", 160, 40); NewClass2 B = new NewClass2("bbb", 170, 60); NewClass2 C = new NewClass2("ccc", 150, 70); System.out.println("---Comparable---"); Set<Comparable> ts3 = new TreeSet<Comparable>(); ts3.add(A); ts3.add(B); ts3.add(C); for(Comparable cm : ts3) { System.out.println(?????????????); } package class; public class NewClass2 implements Comparable< NewClass2> { private String name; private int Weight; private int Height; public String getName() { return this.name; } public void setName(String name) { this.name = name; } public int getWeight() { return this.Weight; } public void setWeight(int Weight) { this.Weight = Weight; } public int getHeight() { return this.Height; } public void setHeight(int Height) { this.Height = Height; } public StudentBean(String name, int Height, int Weight) { this.name = name; this.Weight = Weight; this.Height = Height; } @Override public int compareTo(Object arg0) { StudentBean sb = (StudentBean)arg0;     String name1 = this.name; int Height1 = this.Height; int Weight1 = this.Weight;     int returnval = 0; if(Height1 > sb.getHeight()) { returnval = 1; } else if(Height1 < sb.getHeight()) { returnval = -1; } else returnval = 0; } return ???????; } 文は以上です 出力は aaa 160 40 ・ ・ ・ なかんじでお願いします。

  • JAVAのComparableについて・・・

    compareto()を使って名前、身長、体重を「身長昇順」拡張for文でだしたいのですが・・・ (1)returnを使って何を返せばいいのか? (2)System.out.println()でなにをすればいいのか? (3)他の文で間違っているのか? この3点が分かりません。JAVAに詳しい方よろしくお願いします。。。 package class; public class NewClass { public static void main(String[] args) { NewClass2 A = new NewClass2("aaa", 160, 40); NewClass2 B = new NewClass2("bbb", 170, 60); NewClass2 C = new NewClass2("ccc", 150, 70); System.out.println("---Comparable---"); Set<Comparable> ts3 = new TreeSet<Comparable>(); ts3.add(A); ts3.add(B); ts3.add(C); for(Comparable cm : ts3) { System.out.println(?????????????); } package class; public class NewClass2 implements Comparable< NewClass2> { private String name; private int Weight; private int Height; public String getName() { return this.name; } public void setName(String name) { this.name = name; } public int getWeight() { return this.Weight; } public void setWeight(int Weight) { this.Weight = Weight; } public int getHeight() { return this.Height; } public void setHeight(int Height) { this.Height = Height; } public StudentBean(String name, int Height, int Weight) { this.name = name; this.Weight = Weight; this.Height = Height; } @Override public int compareTo(Object arg0) { StudentBean sb = (StudentBean)arg0;     String name1 = this.name; int Height1 = this.Height; int Weight1 = this.Weight;     int returnval = 0; if(Height1 > sb.getHeight()) { returnval = 1; } else if(Height1 < sb.getHeight()) { returnval = -1; } else returnval = 0; } return ???????; } 文は以上です 出力は aaa 160 40 ・ ・ ・ なかんじでお願いします。

専門家に質問してみよう