Java Thread

neilofbodom

Member
The most correct way would be to use Window Listeners (http://docs.oracle.com/javase/tutorial/uiswing/events/windowlistener.html).

For now hiding the window will work, just make sure you show the old window so you can close it with the X or Alt-F4 or with a System.exit() button (not the cleanest way to close but it will end it) or you might have the process stuck running forever.

I'll update your code and step through it when I get a chance later tonight.

I'll have a look at the Window Listeners. Sounds interesting.

Just to let you know, when I have just 1 question the program works perfectly but when I tried with 2 questions the buttons did not respond and the new question wasn't displayed on the window; the first question just stays there.

Thank you very much, Cromewell! I really appreciate it, you don't know how thankful I am for your generous help.
 

Cromewell

Administrator
Staff member
You are getting some weird behaviour from your UI controls. I added some dummy questions and answers to try and see what you were seeing.

91084063.png


Part of the problem is
Code:
switch (i){
case 0: q[0] = question;
a[0] = choices[0];
a[1] = choices[1];
a[2] = choices[2];
break;
case 1: q[0] = question;
a[3] = choices[0];
a[4] = choices[1];
a[5] = choices[2];
break;
}

Just before the end of build, why are you setting the form to invisible? Removing that line makes the button respond (I get the you're wrong window popping up) but the questions and answers aren't matching up.

Trying to manage all the quesions at once which is causing you problems. Try writing a method which loads up the questions so that you can call it after the user answers a question. You can also use the method to load the first question and call it from the constructor.

edit:
Actually, I'm going to write up a quick class to show you a different way to read and store your questions. You'll need a helper to write the files but when done it will let you do things like have more than 3 possible answers.
 
Last edited:

Cromewell

Administrator
Staff member
So, I made a question class which looks like this:
Code:
import java.io.Serializable;
import java.util.ArrayList;

public class Question implements Serializable { 
	private static final long serialVersionUID = 123456789;
	private String questionText;
	private ArrayList<String> answers;
	private String correctAnswer;
	
	public Question(String q, ArrayList<String> a, String correctA){
		questionText = q;
		answers = a;
		correctAnswer = correctA;
	}
	
	public String getQuestionText(){
		return questionText;
	}
	
	public String getCorrectAnswer(){
		return correctAnswer;
	}
	
	public String[] getAnswersArray(){
		return answers.toArray(new String[answers.size()]);
	}
	
	public ArrayList<String> getAnswers(){
		return answers;
	}
}
Because the class is serializable I can simply make some questions and write them to disk like this:
Code:
//make up some questions
ArrayList<String> ans = new ArrayList<String>();
ArrayList<String> ans2 = new ArrayList<String>();
ArrayList<String> ans3 = new ArrayList<String>();
	
ans.add("England");
ans.add("USA");
ans.add("Ireland");
ans.add("France");
		
Question q1 = new Question("Where was the band Led Zepplin from?", ans, "England");

ans2.add("November Rain");
ans2.add("Sweet Child o' Mine");
ans2.add("Paradise City");
ans2.add("Welcome to the Jungle");
ans2.add("Patience");
ans2.add("Live and Let Die");
		
Question q2 = new Question("What was Guns n' Roses first single?", ans2, "Welcome to the Jungle");

ans3.add("Bon Scott");
ans3.add("Malcolm Young");
ans3.add("Angus Young");

Question q3 = new Question("Who was AC/DC's original lead singer?", ans3, "Bon Scott");

FileOutputStream fos = null; //create an output stream to write the objects to a file
ObjectOutputStream out = null;
try
{
	fos = new FileOutputStream("RockQuestions"); //RockQuestions can be any file name, I didn't include an extension but you could make it whatever you want
	out = new ObjectOutputStream(fos);
	out.writeObject(q1);
	out.writeObject(q2);
	out.writeObject(q3);
	out.close();
}
catch(IOException ex)
{
	ex.printStackTrace();
}
In this case, the defualt object writer from the Serializable interface will do what I want it to do but if you have a more complex object with special rules that need to be saved/read you can override the default writeObject and readObject methods. (http://docs.oracle.com/javase/1.4.2/docs/api/java/io/Serializable.html).

When it comes time to read the questions in, it's just as easy:
Code:
FileInputStream fis = null;
ObjectInputStream in = null;
try
{
	fis = new FileInputStream("RockQuestions");
	in = new ObjectInputStream(fis);

	while (true){ //I couldn't find/remember how to check eof with the object reader so I'm relying on the eof exception being thrown to break out of here...
		questions.add((Question) in.readObject()); //need to cast the read object to the correct type
	}
}
catch(EOFException e){
	System.out.println("Reached EOF"); //this occurs when the entire file has been read
}
catch(IOException ex)
{
	ex.printStackTrace();
}
catch(ClassNotFoundException ex)
{
	ex.printStackTrace();
}
finally {
	if (in != null){ 
		try {
			in.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	if (fis != null){
		try {
			fis.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
I've rewritten your StartRockWindow class to work with the changes, but I'm not going to give that to you, better to try it yourself :)
 

neilofbodom

Member
I haven't had time to work on it so far as I've been busy the past couple of days. I'll have a proper look at what you told me in the weekend hopefully :)

Thank you very much! :D
 

trewyn15

New Member
I have an assignment for class that I need help with, I'm pretty bad at Java but I have an idea of how to do it to an extent. Can you guys read this and see if you can help me get a start? No I don't want you to do my assignment for me, if you can write the full code and explain to me why it works that'd be awesome, but I'm more-so looking for someone to help me start off.

Here it is:

The assignment is to implement a text-based graphics program using composition,
inheritance relationships and polymorphic behaviors (similar to the one we did in class
together) to the one the author does in chapter 9 of the textbook.

We wish to produce a “shapes” taxonomy that would allow for a hierarchy of graphical
objects; such as Points, Lines, Circles, Rectangles, Cylinders and Cubes to be “drawn”.
In order to keep things simple, our drawing for this assignment will only amount to
sending text out to the console (hence the term “Text Graphics” for our assignment).

Arrange these as classes in a hierarchy and associate drawing behavior with each class
that is sensible to draw. (The Shapes class, for instance, would be an abstract class since there’s no reasonable way to draw a generic shape.) The drawing behavior for this
assignment need only consist of text output to the console that states where the shape is and how it would draw itself (just as we did in the example from class).

In your implementation be sure to use both inheritance and composition where
appropriate. Remember, inheritance is called an “IS-A” relationship and composition is
called a “HAS-A” relationship. This rule-of-thumb design principle works for most
simple taxonomies (such as this one).

You’ll also need to use polymorphism in your implementation (i.e. when implementing
the draw() method) so that each shape draws itself appropriately when sent the
draw() message.

Any help is appreciated, thanks guys!
 

Cromewell

Administrator
Staff member
I think the write up gives you a pretty good starting point. Start by making your shape class. Give it properties and methods that all shapes should have (such as the suggested draw, perhaps color is a good property that's common to all shapes).

Once that's done move on to one of the specific shapes. Make sure each shape has everything it needs so that you could draw it if you had to. A sphere might just have a center x/y and radius.

Don't worry about all the buzz words like polymorphism and what not. They will take care of themselves so long as you extend your shape object to make the sub-shapes.

Hopefully that helps a bit. I think all I really did was rehash the wording of your assignment
 

trewyn15

New Member
I think the write up gives you a pretty good starting point. Start by making your shape class. Give it properties and methods that all shapes should have (such as the suggested draw, perhaps color is a good property that's common to all shapes).

Once that's done move on to one of the specific shapes. Make sure each shape has everything it needs so that you could draw it if you had to. A sphere might just have a center x/y and radius.

Don't worry about all the buzz words like polymorphism and what not. They will take care of themselves so long as you extend your shape object to make the sub-shapes.

Hopefully that helps a bit. I think all I really did was rehash the wording of your assignment

thanks for the rewording haha, i'm only in my second year of 'beginners java' I don't really understand how to go about this as far as code goes, this is the first time we've really worked with things that could product an image and the whole hierarchy thing confuses me.
 

Cromewell

Administrator
Staff member
Don't get hung up on how you would actually draw it, at this point it's unimportant.

The heirarchy is simple enough. The choice of words is probably the hardest thing to get around.

You start with
Code:
public class shape {
 //methods and class member variables here.
}
and then your heirarchy is built by doing this:
Code:
public class circle extends shape {
 //methods and class member variables here.
}
It's a lot easier than it sounds just the buzz can easily obscure what you need to do if you are new to the concepts.
 

trewyn15

New Member
okay, i think i'm kind of understanding where you're going with this, i'm not sure if i got this right...

I'm working on another way of this, i will post it when i'm done, so you can let me know if you think i should change anything

public class shape
{ // instance variable
public String toString()
{
return name + " shapes";
}

public static void main(String[] s)
{ // create some objects...
points = new Point("Point");
lines = new Line("Line");
circles = new Circle ("Circle");
rectangles = new Rectangle("Rectangle");
cylinders = new Cylinder("Cylinder");
cubes = new Cube("Cube");
shape = new points();

}
}
 
Last edited:

trewyn15

New Member
starting to get it a little better, still having some compiling errors.

Code:
import java.util.*;

class Line extends Shape {
	private Point start, end;
	private double width;
	protected String name;
	
	Line(String name, Point x, Point y, double w)
	{
		this.name = name;
		start = x;
		end = y;
		width = w;
	}
	
	public String toString() {
		return name + " starts at " + start + " to " + end + " of width = " + width;
	}
}
class fancyLine extends Line{
	private String drawType;
	
	fancyLine(String n, Point a, Point b, double w, String type)
	{
		super(n,a,b,w);
		drawType = type;
	}
	
	public String toString()
	{
		return super.toString() + " and is a " + drawType;
	}
}

class Point extends Shape{ //possibly extends line
	public int x, y, z;
	
	Point(int x, int y) {
	
		this.x = x;
		this.y = y;
	}
	
	Point(Point p) {
		this(p.x, p.y);
		
	}
	
	Point(int x, int y, int z){
		this.x = x;
		this.y = y;
		this.z = z;
	}
	
	public String toString()
	{
		return "(" + x + "," + y +")";
	}
	
}

class Circle extends Shape{ //possibly extend line
	protected double radius;
	protected double center;
	protected double name;
	protected double area;
	
	Circle(String name, Point p, double r) {
		center = p;
		radius = r;
		area = (3.14 * (radius * radius));
		this.name = name;
	}
	
	Circle(String n, Circle x) {
		this.center = center;
		this.radius = radius;
		area = (3.14 * (radius * radius));
		n = name;
	}
	
	public double getArea()
	{
		return Math.PI * Math.pow(radius, 2);
	}
	
	public String toString()
	{
		return name + " originates at " + center + " extends for a radius of " + radius + "the original circles has an area of " + area;
	}
}

class Cylinder extends Circle{
	private int height;
	private Point cylCenter;
	private double cylRadius;
	
	Cylinder(String n, Point x, double r, int h){
		super(n, x, r);
		height = h;
		cylCenter = x;
		cylRadius = r;
		name = n;
	}
	
	Cylinder(String n, Circle x, int h){
		super(n, x, r);
		height = h;
		cylCenter = x;
		cylRadius = r;
		name = n;
	}
		
		public String toString()
		{
			return name + " originates at " + cylCenter + " with a radius of " + cylRadius + " with a height of " + height;
		}
	}	
	
	class Rectangle extends Shape {
		protected Point one, two, three, four;
		protected int height;
		protected String name;
		
	Rectangle(String n, Point start, Point width, Point top){
		name = n;
		one = start;
		two = width;
		three = top;
		
		height = getValy(three) - getValy(one);
		
	}
	
	int getValx (Point x) {
		return x.x;
	}
	
	int getValy (Point y) {
		return y.y;
	}
	
	public String toString()
	{
		return name + " originates at " + one + " its second point is " + two + " and has a height of " + height;
	}
}

class Cube extends Rectangle {
	private int depth;
	
	Cube(String n, Point start, Point width, Point top, int depth) {
		super(n, start, width, top);
		this.depth = depth;
	}
}

abstract class Shape {
	static ArrayList<Shape> container = new ArrayList<Shape>();
	
	public static void main(String args[]) {
		//define the points
		Point origin = new Point (0,0);
		Point twoTwo = new Point (2,2);
		Point twoZero = new Point (2,0);
		Point fourFour = new Point (4,4);
		Point fiveFive = new Point (5,5);	
		Point sixSix = new Point (6,6);
		Point eightEight = new Point (8,8);
		Point zeroZeroFive = new Point (0,0,5);
		Line lineOne = new Line("Line One", origin, twoTwo, 2.1);
		container.add(lineOne); //line
		Line lineTwo = new fancyLine("Line Two", origin, twoTwo, 2.1, "Fancy");
		container.add(lineTwo); //fancy line
		Circle circleOne = new Circle("Circle One", twoTwo, 3.1);
		container.add(circleOne); //circle
		Cylinder cylOne = new Cylinder("Cylinder One", circleOne, 5);
		container.add(cylOne); //cylinder
		Cylinder cylTwo = new Cylinder("Cylinder Two", twoTwo, 3.1, 5);
		container.add(cylTwo); //cylinder method two
		Rectangle recOne = new Rectangle("Rectangle One", origin, twoZero, twoTwo);
		container.add(recOne); //rectangle
		Cube cubeOne = new Cube("Cube One", origin, twoZero, twoTwo, 2);
		container.add(cubeOne); //cube
		
		for (Shape a : container)
			System.out.println(a + " ");
	}
}
 

Cromewell

Administrator
Staff member
Yeah, that's basically it. Don't forget that your instructions require the draw method to be declared in shape and then you implement it in your specific shapes. You pretty much have it done already but you called it toString instead of draw :) It mentions something about how you did it in class, obviously I don't know what that looked like but mimicing it is probably a good idea :p
 

trewyn15

New Member
Thanks for the help, I'm back with some more personal problems haha

We have a take home final and I don't understand what the following questions mean, I think some of it is the way he words it and the other part is my lack of knowledge of java in general. Here are the questions, hopefully you can help :)

1.
Show, by way of example and descriptions, how inheritance works to allow “specializing” an existing class to extend method behavior by “piggybacking” on existing code, rather than having to copy and paste it into the new class.

2.
Show, by way of example and descriptions, how composition works in Java to allow a “subobject” to be stored as an instance variable inside another object. Also, show in your example how the subobject’s data are accessed. Write getter and setter methods for your class.
 

Troncoso

VIP Member
Thanks for the help, I'm back with some more personal problems haha

We have a take home final and I don't understand what the following questions mean, I think some of it is the way he words it and the other part is my lack of knowledge of java in general. Here are the questions, hopefully you can help :)

1.
Show, by way of example and descriptions, how inheritance works to allow “specializing” an existing class to extend method behavior by “piggybacking” on existing code, rather than having to copy and paste it into the new class.

2.
Show, by way of example and descriptions, how composition works in Java to allow a “subobject” to be stored as an instance variable inside another object. Also, show in your example how the subobject’s data are accessed. Write getter and setter methods for your class.

1. is asking you to explain how inheritance allows you to create classes for a more specific purpose, but based on more general classes. Like in the Scientific species tree thing.

order > family > genus > species

Each step further gets more detailed and more specific about the type of living things in that category. In this case, you would write an Order class that had characteristics of anything in that Order. Then you would create a Family class that extends Order, but also include characteristics of creatures only in that family, and so on.

That's the best I can explain it.

The second, I'm not so sure on.
 
Last edited:

trewyn15

New Member
1. is asking you to explain how inheritance allows you to create classes for a more specific purpose, but based on more general classes. Like in the Scientific species tree thing.

order > family > genus > species

Each step further gets more detailed and more specific about the type of living things in that category. In this case, you would write an Order class that had characteristics of anything in that Order. Then you would create a Family class that extends Order, but also include characteristics of creatures only in that family, and so on.

That's the best I can explain it.

The second, I'm not so sure on.

so how would i change this to do what he asks? this is just a 3 level hierarchy of inheritance, i just don't understand what he wants us to do further

Code:
import java.util.ArrayList;

public class Speaker
{  //instance variable
	protected String name;
	public String toString()
	{
		return name + " beats";
	}
	
	public static void main(String[] s)
	{  //creates the types of speakers
		Component alpine = new Sub("Alpine");
		//add those speakers to a container
		ArrayList<Speaker> speakers = new ArrayList<Speaker>();
		speakers.add(alpine);
		//print the above speakers to the console
		for (Speaker a : speakers)
			System.out,print(a + " ");
	}
}

abstract class Component extends Speaker

class Sub extends Component
{
	Sub(String s)
	{ name = s;
	}
	//print representation
	public String toString()
	{
		return name + " makes a bass noise";
	}
}
 

Troncoso

VIP Member
so how would i change this to do what he asks? this is just a 3 level hierarchy of inheritance, i just don't understand what he wants us to do further

Code:
import java.util.ArrayList;

public class Speaker
{  //instance variable
	protected String name;
	public String toString()
	{
		return name + " beats";
	}
	
	public static void main(String[] s)
	{  //creates the types of speakers
		Component alpine = new Sub("Alpine");
		//add those speakers to a container
		ArrayList<Speaker> speakers = new ArrayList<Speaker>();
		speakers.add(alpine);
		//print the above speakers to the console
		for (Speaker a : speakers)
			System.out,print(a + " ");
	}
}

abstract class Component extends Speaker

class Sub extends Component
{
	Sub(String s)
	{ name = s;
	}
	//print representation
	public String toString()
	{
		return name + " makes a bass noise";
	}
}

You have your example, now you need to explain how your code is specializing each level in the hierarchy through re-using code, as opposed to hard coding all 3 classes.

It is against the rules for us to just give you the answer, but I can keep trying to explain it until you understand.
 

trewyn15

New Member
i think i have figure that one out, i am having an issue with this code tho, i'm not sure if it's complete for what the question is.

3. Show, by way of example and descriptions, how composition works in Java to allow a “subobject” to be stored as an instance variable inside another object. Also, show in your example how the subobject’s data are accessed. Write getter and setter methods for your class.

Code:
class Fruit {
	private in age = 0;
	private String ripeness = ripe;
	public void setRipeness(String ripeness){
		this.ripeness = ripeness;}
	public void getAge() {
		return age}  

}

class Apple {
	private Fruit b = new Fruit(fruit);
	
}

thanks for the help so far!
 

Troncoso

VIP Member
Okay, I'm stuck on how to proceed with this issue in an efficient manner. (This is not school work, by the way). But, what I want to do, is take a 7 digit phone number, and list all the possible letter combinations that it can make (based on the dial pad of a regular phone). So, each number corresponds to 3 possible letters:

2 - abc
3 - def
4 - ghi
5 - jkl
6 - mno
7 - prs
8 - tuv
9 - wxy

(I know that the Q and the Z are missing)

So, say I get the number 734-5735, then the first String I could make would be PDGJPDJ.
I'm assuming no number has a 0 or 1.

So, I have this code:

Code:
// numbers is a Character[] ArrayList
public void fillLetters() {
        Character[] n2 = {'a', 'b', 'c'};
        numbers.add(n2);
    
        Character[] n3 = {'d', 'e', 'f'};
        numbers.add(n3);
        
        Character[] n4 = {'g', 'h', 'i'};
        numbers.add(n4);
        
        Character[] n5 = {'j', 'k', 'l'};
        numbers.add(n5);
        
        Character[] n6 = {'m', 'n', 'o'};
        numbers.add(n6);
        
        Character[] n7 = {'p', 'r', 's'};
        numbers.add(n7);
        
        Character[] n8 = {'t', 'u', 'v'};
        numbers.add(n8);
        
        Character[] n9 = {'w', 'x', 'y'};
        numbers.add(n9);
    }
    
    public void writeToFile(int[] nums) {
        int number = 0, letter = 0;
        
        // This is just a place holder. I imagine this format will work 
        // If I can find a way to properly increment through each number and letter
        while (true) {
            for (int i = 0; i < nums.length; i++) {
                pStream.print((char) (numbers.get(i - 2)[letter] - 32));
                System.out.print((char) (numbers.get(i - 2)[letter] - 32));
            }
            pStream.println();
            System.out.println();
        }
    }

All it does so far is print the first String. I can't think of how to make it loop in a way that it will print all 3^7 possible combinations. Any suggestions?

Also, I want it printing to a text file, but I don't feel like opening it every time I run it, so that's what the println's are for.
 
Last edited:

NyxCharon

Active Member
Okay, I'm stuck on how to proceed with this issue in an efficient manner. (This is not school work, by the way). But, what I want to do, is take a 7 digit phone number, and list all the possible letter combinations that it can make (based on the dial pad of a regular phone).

We just did a problem like this in my CS class, but I can not for the life of me remember how we did it. I do remember two being used arrays, and it was recursive. I'll see if I can find the example posted online.
 

Troncoso

VIP Member
We just did a problem like this in my CS class, but I can not for the life of me remember how we did it. I do remember two being used arrays, and it was recursive. I'll see if I can find the example posted online.

Can you clarify what you mean by "two being used arrays". And thanks in advance if you can find it.
 

NyxCharon

Active Member
Can you clarify what you mean by "two being used arrays". And thanks in advance if you can find it.

meant to say, two arrays being used. :eek:

anyways, you're going to have to mod it for your own use obviously, but it might be of some use to you.
Code:
import java.util.*;

public class Permutation {

	public ArrayList<String> getPerms(String s) {

		ArrayList<String> list = new ArrayList<String>();
		if (s.length() == 1)
			list.add(s);
		else {
			for (int i = 0; i < s.length(); i++) {
				char x = s.charAt(i);
				String y = "";
				for (int j = 0; j < s.length(); j++) {
					if (i != j)
						y += s.charAt(j);
				}
				ArrayList<String> results = getPerms(y);
				for (String sf : results) {
					list.add(x + sf);
				}

			}
		}
		return list;

	}

	public static void main(String[] ar) {
		for (String s : new Permutation().getPerms("abcdefg")) {
			System.out.println(s);
		}
	}
}
 
Top