Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

Just a couple of minor changes and you're good to go. First off, int division got you on the 1/count part. This stays zero unless you cast "count" to float. I moved the calc to a variable called "offset". Also, since it was changing by a percentage of diameter, you need to multiply by "r" to get the effect you wanted and I removed the divide by 2, so it filled the area evenly.

The only other changes here are that I moved the drawing call to be after the setColor(), which is usually what you want to do, and I changed it to fillOval() instead of drawOval() so it wasn't just line drawings.

public static void bullseye(Graphics g, int x, int y, int diam, int count) {
    int r = diam;   // because fillOval uses width and height, use diam here
    int xloc = x;
    int yloc = y;

    boolean change = true;
    for(int j=0;j<count;j++) {
        // must cast int divisor to float
        // then cast the final result back to int.
        // also multiplying by r so it's a percentage of diam
        int offset = (int)(r*(j*(1/(float)count)));
        if(change) {
            g.setColor(Color.BLACK);
            change = false;
        } else {
            g.setColor(Color.RED);
            change = true;
        }
        g.fillOval(xloc+offset/2, yloc+offset/2, r-offset, r-offset);
    }
}
Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

Either make sure the balls can get there or don't let the user go that far into the corners.

Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

Looks good. One additional change I would suggest though: put the code that updates the ball postions and creates a new one when needed over into a separate method like "updateBalls()" and call that before repaint in your animation loop. Repaint should generally make as few calculations as possible, since it gets called for all sorts of reasons at any time (window resizings, parts of the window becoming occluded, etc). You have the ball coordinates all encapsulated in the Ball class, so this should be very easy to extract to a new method.
Your paint() method can just loop the array list and draw each ball as needed. Always try to keep paint() (or paintComponent() ) as narrowly focused on it's task of just rendering things as possible and your interface will be much happier and lag-free.

Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

i thought of doing it in that way but it still doesnt works.
Anyone that can help me???
Thanks.

import java.util.Scanner;
import java.util.*;
public class grid
{
    
    private int rows;
    private int columns;
    private ArrayList<String> myArray;
    
    //static Scanner sc = new Scanner(System.in);
    private int row;
    private int colu;
    
    public void RowColumns(int rows, int columns)
    {
        ArrayList[][] myArray = new ArrayList[rows][columns];
    }
    //public void write(String r, String c)
    //{
      //for (int i=0; i<= columns; i++){
    //}
    public void addString (int row, int column, String myString) {
        for (int i=0; (i<columns);i++);{
            for (int j=0; j<rows;j++);{
                myArray[columns][rows]= Console.readLine();
            }
        }
        //myArray[rows][columns] = myString;
    }  
}

Ok, you got closer on some parts and further away on others. First off, you need a array of String[][] - not ArrayList[][], which is an array of ArrayList objects. So change the array definition to be String[][].

You do need the Scanner to read the input, uncomment that.
If you need to read the input for a single row-column cell in your addString method, then you don't need to loop all of the array. You just need to read the single entry

System.out.println("Enter string:");
myArray[row][col] = sc.readLine();

and that is all. You don't need the myString parameter on the method, just the row and column. Whatever method is calling addString() is the one that needs to loop through all rows and columns, calling addString() for each position.
I think you need to step back a little and think about the steps …

Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

Here are the minimal changes to get it running as a JFrame

/*Main Menu Graphical User Interface
 * Phillip Wells 10/12/07
 */

import javax.swing.*;
import java.awt.event.*;
import java.awt.*;


public class MenuGUI extends JFrame 
{
    public static void main (String [] args)
    {
    new MenuGUI();
    }


private JButton buttonnew, buttonexit;
private JLabel label1;

public MenuGUI()
    {
    this.setSize(250,100);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setTitle("Game");
    
    ButtonListener b1 = new ButtonListener();

    JPanel panel1 = new JPanel();
    buttonnew = new JButton("New Game");
    buttonnew.addActionListener(b1);
    panel1.add(buttonnew);
    this.add(panel1);
    
    buttonexit = new JButton("Exit Game");
    buttonexit.addActionListener(b1);
    panel1.add(buttonexit);
        
    label1 = new JLabel("Phillip Wells");
    panel1.add(label1);
      
    this.setVisible(true);
    }

private class ButtonListener implements ActionListener
    {
        public void actionPerformed(ActionEvent e)
        {
            if (e.getSource() == buttonnew)
            {
                NotPong game = new NotPong();
                game.init();
            }    
            else if (e.getSource() == buttonexit)
            {
                System.exit(0);
            }
        }
    }    


}
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.geom.*;
import java.util.concurrent.*;

public class NotPong extends JFrame {
    public static final int WIDTH = 400;
    public static final int HEIGHT = 400;
    
    private PaintSurface canvas;
    
    public void init() {
        this.setSize(WIDTH, HEIGHT);
        canvas = new PaintSurface();
        this.getContentPane().add(canvas, BorderLayout.CENTER);
        ScheduledThreadPoolExecutor executor =
                new ScheduledThreadPoolExecutor(3);
        executor.scheduleAtFixedRate(new AnimationThread(this),
                0L, 20L, TimeUnit.MILLISECONDS);
        setVisible(true);
    }
    
    
    
    class AnimationThread implements Runnable {
        JFrame c;
        
        public AnimationThread(JFrame c) {
            this.c = c;
        }
        
        public void run() {
            c.repaint();
        }
    }
    
    class PaintSurface extends JComponent {
        int paddle_x = 0;
        int paddle_y = 360;
        
        int score = 0;
        float english = 1.0f;
        
        Ball ball;
        
        Color[] color = {Color.RED, Color.ORANGE,
        Color.MAGENTA, Color.ORANGE,
        Color.CYAN, Color.BLUE};
        int colorIndex;
        
        public PaintSurface() {
            addMouseMotionListener(new MouseMotionAdapter() {
                public void mouseMoved(MouseEvent e) …
Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

Ah, your game is an applet. You should convert it to a JFrame or JPanel if you wish to run it from your GUI. That is only a minimal bit of work. You'll need to do the init() work in either your constructor or call the method yourself after you have created the NotPong object. You'll also need to create a run() method that creates and starts a new Animator thread.

Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

Read the API for Scanner . It shows basic usage right there in the javadocs. Try it out and repost your code if you are still having difficulties getting it to work.

Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

So, to reiterate what everyone else has already told you, the answer is essentially
NO.
If you need an installer that will install java for a user if they don't already have it, take a look at http://izpack.org/.

Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

Your handler just needs to create an instance of the game class if you don't already have one and call whatever method starts the game

Game game = new Game();
game.start();
Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

Perhaps some of the info in this post might help:
http://forum.java.sun.com/thread.jspa?threadID=5137992&messageID=9506454

Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

Everyone working with Java should take the time to read the Java coding conventions published by Sun: http://java.sun.com/docs/codeconv/html/CodeConvTOC.doc.html
Coding to the common conventions will ensure a consistency that greatly aids both the coder and others reading that code.

Anyone designing programs that involve more than one or two classes could benefit from familiarizing themselves with design patterns. An excellent introduction to this is Head First Design Patterns. Design patterns may or may not be appropriate for a given application, but learning about them and their usage will teach you to look at your program organization in a more critical manner from perspectives that you may not have considered at the outset.

Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

Yes, EatDot() needs to be called before repaint() in your KeyAdapter to evaluate if a dot is eaten.

Also, your collision function in EatDot() needs to check the absolute value of the coordinate differences

if ((Math.abs(xcoords - dot[i].x) <= 5) && ((Math.abs(ycoords - dot[i].y) <=5)) && !dot[i].isEaten()) {

and lastly you need to reevaluate your offsets from xcoords and ycoords in your placement and drawing of the pacman arc. Offsetting -50 from x and y are causing your pacman to be drawn in the wrong location relative to xcoords and ycoords values you are checking against the dot coordinates.

You are close. You just need to check your relative coordinate and bounding box usage to fine tune it.

You might want to also use an ArrayList for the Dots instead of a fixed 1000 element array and remove a dot when it is eaten, rather than leaving it in an array and continuing to check it after it's long gone.

darkagn commented: Good points all +1
Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

Just to give the solution to everyone (we worked it out over IRC).
I think the getClass() method didn't really do what it was supposed to be doing. Instead using ClassName.class.getResource() did the job.

Black Box

Glad you got it worked out there. getClass() works fine in our app context here, but as usual with varying application structures, you have to fiddle around a bit sometimes to get context issues resolved.

You can probably even ditch the URL variable and just use the original string path, since you're turning around and calling getPath on the URL in the getResource() call.

Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

My bad, brackets problem... the Image returns a Image not an ImageIcon... I guess that raises the question as to whether I'm ment to be using ~Image or ImageIcon... Interesting...

That just depends on what else you are doing with it :) If a method needs an Image reference you can just call getImage() if you have an existing ImageIcon object.

Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

the .getImage() isn't a functiuon thats assicated with this file type??

Sorry, mistype from hacking two different sources together

new ImageIcon(getClass().getResource(IMAGE_NOTBROADCAST_URL.getPath ())).getImage()

if "img" is an Image reference. If it's an ImageIcon, then you don't need the getImage() call;

Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

Try

new ImageIcon( getClass().getResource(IMAGE_NOTBROADCAST_URL.getPath ())).getImage()

. You may need to alter the classpath as well.

Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

Your IDE is most likely treating it's project root directory as the root context when it executes. If you are clicking on a jar in the dist folder, that is most likely the root context. Try dropping a copy of your images directory into the dist folder. If it runs fine then you'll know that is the issue.

We actually include our images folder on the classpath and use

getClass().getResource(imagePath)).getImage()

to load an image.

Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

Date is actually deprecated and should be replaced with Calendar

java.util.Calendar now = java.util.Calendar.getInstance();
String currentTime= java.text.SimpleDateFormat.getInstance().format(now.getTime());
Ezzaral 2,714 Posting Sage Team Colleague Featured Poster
JToggleButton[][] buttons = new JToggleButton[5][5];

That just declares the type and dimensions. You still have to set each element equal to a new instance of JToggleButton.

Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

You may be able to get the 0-255 grayscale value like this

int grayVal = ((int) sample2[0]) & 0xff;

(I haven't worked with it myself, but some reading suggests that might work for you.)

Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

Hibernate will work with H2 and McKoi as well, so you can still use an embedded database without a server installation.

Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

For those images, you can store the path to it.

Agreed. I'd recommend that even with a database.

Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

It depends on how you need to access the data, but I would imagine the simple file would suffice. You don't mention what the data is, but basically you have the equivalent of a single table. With file-based storage you will need to write the methods yourself if you want to query the data in any manner. If such queries are straightforward, such as just finding a couple entries based on simple criteria, you really don't need the database.

That said, if you expect to grow to have several other tables of information and will need to correlate information between them in a variety of ways, you should go ahead and start with a database.

McKoi and H2 are a couple of good open-source Java embedded databases (they don't need a separate installation on a server) if you decide you want to use the database.

Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

See this is what I'm confused about: how do I know what I'm going to compare given that the compareTo() method is supposed to be able take any type of object argument? Different data types added to DataSet may require different methods of measurements (i.e. for strings you compare their length; numbers, magnitude; etc..). Somehow, I don't see a way to do this for generic objects, even with casting. There must be something I'm forgetting here.

edit: no emoticons -.-||

You could use instanceof to check the type of the object and operate appropriately. Any object that is of a numerical wrapper type (Integer, Long, etc.) extends Number, so that check becomes easy, as you can see here

Integer a = 3;
Integer b = 2;

if (a instanceof Number){
    if (a < b)
        System.out.println("-1");  // just printing here as example
    else if (a > b)
        System.out.println("1");
    else
        System.out.println("0");
}

If the object is an instanceof String, those operations can be separated the same way.

Since you have a parameter of Object to be compared to "this", you will also need to decide what to do if they are not compatible types. The compareTo() method says that it will throw ClassCastException if the types are not comparable, so you need to throw that exception unless you have a specific strategy on comparing disparate types (ie by their toString() values, or perhaps treating Strings as a numeric zero, etc). Most likely you would want to throw the exception, since …

Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

It sounds like you mostly understand how compareTo(Object o) works. Your job is to compare the specific properties of the objects in your if() statements such that you return the proper int value. If you need to compare on some property value, say object.cost() for example, you write the if() statements to copare those properties such that if o1.cost()<o2.cost() then return -1, etc. If you aren't using generics to define the object types, then you will need to case Object to the correct type before you can access the properties.

I think you almost have it nailed well enough, but if my explanation is still confusing, just post back on what you don't understand.

Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

One more very handy site for code snippet examples on many things:
Java Examples from The Java Developers Almanac 1.4

emaan.gseo1 commented: nice post +0
Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

Yes, something like what S.O.S. posted was what I had in mind, and you'll notice that it does still show exception handling as your assignment required.

It may make no difference to your current assignment, but keep such things in mind for future consideration when your initial plan yields duplicate code blocks.

Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

By giving your arrays to that method, you give them a local copy of the arrays.
This means that what ever you do inside that method, happens to the copy. In orde to get the result back into your initial arrays, you need to let your methods return the adjustments you made.

Actually, no, any operations he performs on the elements of the passed array do affect the original. It does not make a copy of the array.

rickster11,
The reason for the error is that you are not checking the length of the array in your loop, just for the end of file. You have declared the arrays to have five elements, but you are not hitting "eof" on the fifth read so it has incremented "x" and is trying to access an array element that doesn't exist. Make sure that your loop also checks against the array length to avoid this.

edit: Additionally, your "y" variable remains 0 as it is, so you will never have data past the first element in that dimension of your array.

Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

A counter of the incorrect entries would be easier. What if you decided to allow for three incorrect entries instead of two? Another try block with identical code would be needed. In most all cases, duplicate code blocks should suggest to you that something could be arranged more efficiently.

Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

You are merely scanning all the words and incrementing the position, but you don't do anything when you get to the position where the insertion is to take place. The for loop is just printing the last word found by the scanner "number of words" times.

You are also returning a recursive call back into the same function, which is definitely not what you want to do. You need to return the new sentence string (which you haven't created).

Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

You just have the boolean values reversed in the conditions

if ( numerator != -99) {
                    int result = quotient( numerator, denominator );
                    System.out.printf( "\nResult: %d / %d = %d\n", numerator,
                      denominator, result );
                    //continueLoop = true;   don't even need this one
                } else {
                    continueLoop = false;  // set to false if -99
                }
DeadJustice commented: Thanks again! +1
Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

hmm 400 is way over my budget haha i'm a broke college student so i'll do what i can

Cheaper and more productive to just do your own homework.

Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

You'll need to use a formatter like DecimalFormat or String.format().

float value = 0.60f;
DecimalFormat df = new DecimalFormat("0.00");
String formattedValue = df.format(value);
Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

Many of the javax packages are included in the JDK distribution. A few of them, however, are separate downloads on the Sun site. The media framework is one of them. You can get it here: http://java.sun.com/products/java-media/jmf/

Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

I ended up using this ...

fout = new FileOutputStream ("c:\\afmd.tmp");
new PrintStream(fout).println ("xxBL," + textBL.getText());
new PrintStream(fout).println ("xxBA," + textBA.getText());

You do not need to create a new PrintStream for each call.

Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

anyone?

Anyone what?
If you're talking about your "driver class" question, just write your own if you really want to (though I can't see why for the life of me). There is only one constructor and one method of any external consequence.

Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

http://java.sun.com/javase/6/docs/api/java/util/Scanner.html can be used for scanning and processing many kinds of text input from a variety of sources.

http://java.sun.com/javase/6/docs/api/java/io/BufferedReader.html allows for buffered reading from an input stream and has a readLine() method that will read a single line from a stream (file in your case).

String.split() http://java.sun.com/javase/6/docs/api/java/lang/String.html#split(java.lang.String) splits a string by the supplied expression and returns the pieces as an array of strings.

The following code fragment opens a BufferedReader against a text file and reads each line.

try {
            BufferedReader reader = new BufferedReader(new FileReader("file.txt"));
            
            String line = null;
            while ((line = reader.readLine()) != null){
                System.out.println(line);
            }
        } catch (Exception e){
            e.printStackTrace();
        }

With that as a starting point, see if you can get the elements into your array and post back if you run into problems.

Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

You can use Scanner or a BufferedReader and String.split().

Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

Make the method static.

Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

Ummmm okay, I'm going to state my problem again, cause My problem still isn't fixed...... Alright, so I thought I was doing everything correct, and it looks like it should be coming But, for some reason, the points that are made are not appearing inside the triangle, instead they make a line along the edge of the triangle! I put my problem in Italics, it would be great if someone could tell me why this is happening!

Well, for one thing, you were not calculating the inner point correctly. The code that I reworked a bit for you does give a random inside point, without some of the hassles you were having with the data structures. Since I already took the time to get that working for you, I'm not much inclined to fiddle any more with it. By the way - you're welcome.

edit:

Oh, and tell me anything that might make it better, but simple

Which I did...

Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

They can be useful as small data structures or "helper" objects that only have applicability in the context of their enclosing class. S.O.S. posted an example of such a case above. The 'Entry' is really only useful with the HashMap. It could be published as a full public class, but if it is not used by other classes then it just clutters the API. As a static inner class of HashMap, its usage is clearly scoped.

Jishnu commented: This was helpful. +2
Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

So have you come up with an answer to this homework question yet? When do you think they could be useful?

Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

Try this as a starting point

import java.awt.geom.Rectangle2D;
import javax.swing.JFrame;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Random;
import java.util.ArrayList;


public class Fractal extends JPanel
{
    private int[] triangle01 = {150, 300, 150};
    private int[] triangle02 = {300, 300, 150};

    Random gen = new Random();
    ArrayList<Point> dots = new ArrayList<Point>();  //holds all the points that are made in this program

    Polygon triangle = new Polygon(triangle01, triangle02, triangle01.length);

	public Fractal ()
	{
    	addKeyListener (new DirectionListener());
    	setFocusable(true);
    	setBackground (Color.black);
    	setPreferredSize (new Dimension (1000,1000));
	}


    public static void main(String[] args)
    {
        JFrame frame = new JFrame ("Fractal");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        Fractal panel = new Fractal();

        frame.getContentPane().add(panel);
        frame.pack();
        frame.setVisible(true);
    }
    
    public void paintComponent (Graphics page)
    {
        Graphics2D g2d = (Graphics2D)page;
        g2d.setBackground(Color.black);
        g2d.clearRect(0,0,getWidth(), getHeight());
        g2d.setColor(Color.red);
        for (Point p : dots){
            g2d.fillRect(p.x,p.y,1,1);
        }
        g2d.setColor(Color.white);
        g2d.drawPolygon(triangle);
    }

    
    public void createFractalPoint(Polygon poly){
        Point inner = getInnerPoint(poly);
        Point vertex = getVertex(poly);
        dots.add( getMidpoint(inner, vertex) );
    }

    public Point getInnerPoint(Polygon poly){
        Rectangle2D bounds = poly.getBounds2D();
        Point p;
        do {
            p = new Point((int)(bounds.getMinX() + gen.nextFloat()*bounds.getWidth()),(int)(bounds.getMinY() + gen.nextFloat()*bounds.getHeight()));
        } while (!poly.contains(p));
        return p;
    }
    
    public Point getVertex(Polygon poly){
        int index = gen.nextInt(poly.npoints);
        return new Point(poly.xpoints[index], poly.ypoints[index]);
    }
    
    public Point getMidpoint(Point p1, Point p2) {
        return new Point((int)((p1.x+p2.x)/2), (int)((p1.y+p2.y)/2));
    }


    private class DirectionListener implements KeyListener
    {
        public void keyPressed (KeyEvent event)
        {
            createFractalPoint(triangle);
            repaint();
        }
        public void keyTyped (KeyEvent event) {}
        public void keyReleased (KeyEvent event) {}
    }
}

This still gives you some room to grow on. You are just using the midpoint, but the algorithm calls for a random distance between …

Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

Actually, you give him more credit than is due. He isn't even asking a question - just reposting a piece of the original post. He seems to have done that in a lot of other threads as well. He just reposts a random piece of what someone else posted, adding no useful information whatsoever.

Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

replaceAll(" ","")

Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

Well, the code you posted does not have anything written to do either of those things. If you are having trouble with an updated version of it, you'll need to post that with your question. We can't discuss what we can't see very well.

Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

Yes, please find the question below:
<snipped>

No, posting your homework assignment does not constitute specific questions. You need to make an effort to complete the assignment on your own. If you have difficulties, then post the code and the errors or questions you cannot figure out.

Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

Sure, the first thing that would help is filling in those methods a bit more.

Did you have any other specific questions?

Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

Are you sure you have compiled it after recent changes? You program worked just fine for me. I was able to enter the number of elements that I had set ARRAY1 to hold with no errors.

Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

Online gaming forums are doomed.