I have the following method in one of my classes called Board. Board has an array of 120 Squares, which is another class from my program.
public class Board{
private Square[] square = new Square[120];
...
Each Square has an int row and an int column.
public class Square extends JButton{
public int row;
public int column;
...
The method itself is supposed to figure out what the row and column is for every Square inside
void setSquares() {
int ones;
int tenths;
Square s = new Square();
Insets squareMargin = new Insets(5, 5, 5, 5);
s.setMargin(squareMargin);
for (int i = 0; i < square.length; i++){
ones = getNdigit(i, 1);
tenths = getNdigit(i, 2);
//set row && set column
if ((tenths >= 2 && tenths <= 9) && (ones >= 1 && ones <= 8)){
s.row = tenths - 1;
s.column = ones;
} else{
s.row = 0;
s.column = 0;
}
square[i] = s;
System.out.println(square[0].toString());
}
So at the end of the method, I expect that square[34] has a row of 2 and a column of 4. However, the actual result is always the same as where the for loop ended (square[34] has a row and column of 0).
If the for loop was changed to
for (int i = 0; i < 55; i++){
then square[34] has a row of 4 and a column of 4.
You are creating only one instance of Square and use it throughout the for loop. Move the instantiation inside the for loop so each instance stored will be different.
To answer your question in the comment:
Square s = new Square();
Allocates some space in memory to store the Square instance (where you can set values to its members). so now s references that space in memory.
square[i] = s;
so now square[i] references that same space (thus having the same member values). so for every i all square[i] references to the same place (the same instance of Square). But if you allocate s one each iteration then s will reference a new square and each square[i] will reference a different Square instance
Related
I am trying to finish my code for an assignment I have, but I'm stuck on the last component. I need to create "stars" (small yellow square objects) in the "sky"... a grid of 5 rows of 10 stars. I am in a beginner java class, and I am supposed to being using methods such as star.moveHorizontal() or star.moveVertical(). All of the relevant posts I've searched for have been too complex or out of my comprehension.
I think that I would need to create an array? We haven't even covered that in class... And then have each "star" be x distance (the first star) + 30 units to the right. Then t continue that trend until there are 10 stars in a row. And then get four more rows of 10 stars.
Here is the code I've create for just one star (in the upper left of my window):
Square s1 = new Square();
s1.makeVisible();
s1.changeColor("yellow");
s1.changeSize(5);
s1.moveVertical(-100);
s1.moveHorizontal(-270);
Then I tried to create an array for a square class... I honestly have no idea if that's even legal.
Square[] starArray = new Square[10];
for ( int i=0; i<starArray.length; i++) {
starArray[i] = new Square();
But then I don't understand how I can call each star and make them appear... Please help. I feel so out of my depth. I've tried to research this and try new things for over 2.5 hours now. I will answer any questions you have to the best of my ability. Thank you
If you can make a single star appear and haven't learned about arrays yet, I don't think that is the answer your teacher is looking for. The point of an array is to be a container so you can reference the objects again. If you don't need to go back to the stars in the future, just create them and set their values in a loop.
// Set defaults for spacing and start positions
int horizontalStartPosition = 10;
int horizontalSpacing = 30;
int verticalStartPosition = 10;
int verticalSpacing = 30;
// Outer loop creates the 4 rows
for (int i = 0; i < 4; i++) {
// Inner loop creates each row
for (int j = 0; j < 10; j++) {
// Create the next star in the row
Square s = new Square();
s.makeVisible();
s.changeColor("yellow");
s.changeSize(5);
// Move the star to the correct vertical position for the current row
s.moveVertical(verticalStartPosition + i * verticalSpacing);
// Move the star to the correct horizontal spacing for the next star
s.moveHorizontal(horizontalStartPosition + j * horizontalSpacing);
}
}
You're on the right track. You can use a 2D array with 5 rows and 10 columns. Try something like this:
int numColumns = 10; //the number of columns in the array
int numRows = 5; // the number of rows in the array
Square[][] starArray = new Square[numRows][numColumns]; // the array itself
final int DIST_X = 10; //the distance between columns (use final because this value should not change)
final int DIST_Y = 10; // the distance between rows (use final because this value should not change)
int y = 0; // the initial row's vertical displacement
for ( int i=0; i<numRows; i++) {
int x = 0; // the initial columns horizontal displacement
for ( int j=0; j<numColumns; j++) {
starArray[i][j] = new Square(); //define the square
starArray[i][j].moveHorizontal(x); // move it x units horizontally
starArray[i][j].moveVertical(y); // move it y units vertically
starArray[i][j].makeVisible(); //show the square
x += DIST_X; //update your horizontal displacement so the next column shows up in the correct position
}
y += DIST_Y; //update your vertical displacement so the next row shows up in the correct position
}
Based on what I understand, you would want to call a method which would basically place a star in the grid for you.
I am not fully sure of what you mean, but here is what I can offer you:
You'll want to create a method for placing a star.
private static int X_SPACING = 30;
private static int Y_SPACING = 20;
public Square placeStar(int x, int y){
// This is the same code that you had before.
Square sq = new Square();
sq.changeColor("yellow");
sq.changeSize(5);
sq.moveVertical(-y); // Where Y is the distance from the TOP LEFT.
sq.moveHorizontal(-x);
return sq;
}
public ArrayList<Square> makeRow(int columnsAmount, int y, int startX){
ArrayList<Square> squares = new ArrayList<>();
for(int i = 0; i < columnsAmount; i++)
squares.add(placeStar(startX + (X_SPACING * i), y));
return squares;
}
public ArrayList<Square> makeGrid(int rowsAmount, int columnsAmount){
ArrayList<Square> rslt = new ArrayList<>();
for(int i = 0; i < rowsAmount; i++)
rslt.addAll(makeRow(columnsAmount, (i * Y_SPACING), 0);
return rslt;
}
Basically, calling "makeRow" should create a row of [rowsAmount] stars, which are all separated by [X_SPACING] pixels.
Then, makeGrid will call makeRow multiple times adjusting [y], and this will make you a grid. Feel free to adjust any value in the code.
EDIT: I've added a makeGrid function, and changed a few variables in the makeRow as I mistyped them. I made the functions return an ArrayList, but you shouldn't need them, only if your teachers later ask to modify them later, or something.
I hope this helps, don't hesitate to ask more questions.
Sneling.
So im new to Stack Overflow and hope I am saying this question correctly.
I was given this assignment from class and was done with it until my professor tweak the assignment a little bit. In summary i made 2 classes the would work with each other and call off the variable from the other class into the class it was being called to. Now my professor want 1 java file which mean one class file. I do not know how to rewrite the program with both code into one class.
Assignment:
"(The Location class) Design a class named Location for locating a maximal value and its location in a two-dimensional array. The class contains public data fields row, column, and maxValue that store the maximal value and its indices in a two-dimensional array with row and column as int types and maxValue as double type.
Write the following method that returns the location of the largest element in a two-dimensional array:
public static Location locateLargest(double[][] a)
The return value is an instance of Location. Write a test program that prompts the user to enter two-dimensional array and displays the location of the largest element in the array. Here is sample run:
Enter the number of rows and columns of the array: 3 4
Enter the array:
23.5 35 2 10
4.5 3 45 3.5
35 44 5.5 9.6
The location of the largest element is 45 at (1, 2)
SO i did all that with the 1st class coding:
public class Location {
int row; //blue variable = class variable
int column;
double maxValue;
}
Then here the code that call in the program in the second class
import java.util .*;
public class TestLocation {
public static void main(String[] args)
{
Location mylocation;
int row;
int column;
double [][] numArray; //we can leave this blank
Scanner Reading = new Scanner(System.in);
System.out.println(" How many rows will you be entering?");
row = Reading.nextInt(); //nextInt -what it reads will convert into a integer
System.out.println(" How many columns will you be entering?");
column = Reading.nextInt();
numArray = new double [row][column];
System.out.println("Enter the array please");
for (int i = 0; i < row; i++)
{
for (int j = 0; j < column; j++)
{
numArray[i][j] = Reading.nextDouble();
//i is the row and j is the column
}
}
mylocation = locateLargest(numArray);
int temp = (int)mylocation.maxValue; //this is to print out the difference between int and double(decimal)
if (temp == mylocation.maxValue)
System.out.println("Highest Number: " +(int)mylocation.maxValue); //(int forces to be an integer then the double it was, eliminate decimal places)
else
System.out.println("Highest Number: " +mylocation.maxValue); //print out with decimal
System.out.println("Position: (" + mylocation.row+", " + mylocation.column +")");
Reading.close();
}
public static Location locateLargest(double[][] a)
{
Location mylocation = new Location(); //this is where we are going to store my information in
mylocation.maxValue = a[0][0]; //this is the max value to the first number
mylocation.row = 0;
mylocation.column = 0;
for (int i = 0; i < a.length; i++) //Length of the row; how many row there are
{
for (int j = 0; j < a[0].length; j++) //Length of a row; how many column in that row
//we added array here in the second because we want of get the length of the second dimension
//.length get the length of the current dimension , so a.length get the length of the first dimension
{
if (mylocation.maxValue < a[i][j] )
{
mylocation.maxValue = a[i][j];
mylocation.row = i;
mylocation.column = j;
}
}
}
return mylocation;
}
}
how can i reprogram this with the new instruction that was in the assignment box above that require me to but all the coding into one class = 1 java file? I tried almost everything And could not get the results i want.
One java file only allows one public class file. Remove public keyword from the first java file, and put them into the same file as the second one will work.
class Location {
int row; //blue variable = class variable
int column;
double maxValue;
}
I'm trying to make a game for an assignment called PegSwap. They dynamics of the game aren't important, but the "board" is a board with 7 spaces. 3 red pegs, 3 blue pegs, at random positions, with a blank spot in the middle. All I'm trying to do is randomly generate the initial positions of each peg. Here is my code:
package game;
import java.util.List;
public class PegGame implements GameState {
//numbers corresponding to beg color to be used in list
private final int BLANK = 3;
private final int BLUE = 1;
private final int RED = 2;
//list that maintains peg at position i
private int[] pegs = new int[7];
//generates a randomized start state for the board
public int[] startState(){
int blues = 0;// how many blues have been added so far?
int reds = 0; //how many reds have been added so far?
pegs[3] = 3; //puts blank spot in the center
for(int i = 1; i<6; i++){
if(i == 3) break;
else if(blues < 3 && reds < 3) pegs[i] = (int) (Math.random()*2);
else{
if(blues == 3) pegs[i] = 2;
if(reds == 3)pegs[i] = 1;
}
}
return pegs;
}
The problem is, where I refer to the integer list pegs in the 'startState' method, (the line that says pegs[3] = 3) Eclipse is giving me an error, saying pegs is an unresolved type. Why is it unresolved if I declare it to be an integer array right above the method? I don't get the error on any other references to pegs. I thought maybe it was because pegs has to be passed into startState, but this just gives me more errors saying that pegs must be static. Can anyone help?
Edit:
Could it really be because it's private? Doesn't that just mean it can't be accessed in other classes? I also had to write a winState method, and the references to pegs rose no errors at all, it is just that one refernce.
public int[] winState(){
for(int i=0; i<6; i++){
if(pegs[i] == 3) pegs[i] = 3;
if(pegs[i] == 2) pegs[i] = 1;
if(pegs[i] == 1) pegs[i] = 2;
}
return pegs;
}
I don't think there is problem in your code.
This should work. Try cleaning and rebuilding.
If doesn't work.
Please provide what exactly problem given at your console.
this may be an easy one, but I'm getting an out of bounds exception and I'm not sure how to fix it.
Basically, I am trying to create a "table" of integer fields so that I can use them to find if all of the values in the integer fields create a magic square. The nested for loop should create up to an 8x8 square, and it will create the first row of the square, but instead it gives me an out of bounds error.
The error occurs inside of the nested for loop where I'm adding the IntegerField to the GUI.
If anyone can help, that would be great. Let me know if you need more details.
import javax.swing.*;
import BreezySwing.*;
public class Interface extends GBFrame{
//Create integerField array to create input for magic square
public IntegerField[][] magicSquare;
//Create input button, integer field which sets size of square
public IntegerField squareSize;
public JButton inputSize;
//Create check square button
public JButton checkSquare;
//Label to output if there is a magic square
public JLabel squareLabel;
//Size of square variable
public int size;
//CalcSquare object
CalcSquare calc = new CalcSquare();
//Constructor for Square interface
public Interface()
{
squareSize = addIntegerField (0, 1, 1, 1, 1);
inputSize = addButton ("Input Size", 2, 1, 1, 1);
squareLabel = addLabel ("", 3, 1, 1, 1);
checkSquare = addButton ("Check Square", 4, 1, 1, 1);
}
//Creates IntegerFields on the GUI as needed.
public void createFields()
{
for (int i = 0; i <= size; i++)
{
for (int x = 0; x <= size; x++)
{
magicSquare = new IntegerField[i][x];
}
}
}
public void buttonClicked(JButton buttonObj)
{
if (buttonObj == inputSize)
{
size = squareSize.getNumber();
createFields();
for (int i = 0; i <= size; i++)
{
for (int x = 0; x <= size; x++)
{
magicSquare[i][x] = addIntegerField (0, i+1, x+1, 1, 1);
}
}
}
else if (buttonObj == checkSquare)
{
}
}
}
A for loop condition of i <= size Should always raise red flags since if i == size, you've gone beyond the size of the array or collection. Note that arrays and collections are 0 based and go from 0 to size - 1.
It should instead almost always be i < size
All your loops are iterating upto size which will cause ArrayIndexOutOfBoundException. The Array index starts from 0 to size-1. Here is one of such loop in your code:
for (int i = 0; i <= size; i++)
you need to iterate the loop only till size
for (int i = 0; i < size; i++)
Correct other loops accordingly
size is never initialized. And your <= should be < in the for loops.
In fact, if you're using size as a constant to set the size of your arrays, you should use i < size - 1 in for loops.
I'm trying to create a pyramid of circles to my game, looking similar to this :
alt text http://img266.imageshack.us/img266/3094/lab1213c.jpg
But I can't make it print properly. Constantly I'm getting really strange spirals but nothing close to this. Can anyone give me some tip on proper formula ? My window is 600x600, base of pyramid is 8 .
fields = new Field[BASE*(BASE/2)+4];
int line_count = BASE;
int line_tmp = line_count;
for(int i=0; i< fields.length; i++){
for( int j=line_tmp; j <= line_count; j++){
fields[i] = new Field(0, (150+(line_tmp*5)),(600+line_tmp*5));
}
line_count--;
line_tmp = line_count;
}
The mistakes I see are:
Incorrect array size formula.
Including line_tmp (which seems to be your column counter) in your y expression.
Having two variables, line_count and line_temp that are always equal.
Having your outer loop count by node rather than counting by row.
Having generally meaningless variable names and magic numbers strewn about.
// I use java.util.ArrayList because using its add(..) method is convenient here.
// The proper forumula for anticipated number of nodes is: base×(base+1)÷2
final List<Field> fields = new ArrayList<Field>(BASE*(BASE+1)/2);
// I use a java.awt.Point to store the (x,y) value of the first node of the row.
// This clarifies the meaning, rather than using ints or long inline expressions.
final Point rowStart = new Point(PANEL_WIDTH/2, DIAMETER);
// The number of rows equals the number of nodes on the final row.
for (int row = 1; row <= BASE; row++) {
// The nth row has n nodes.
for (int circle = 0; circle < row; circle++) {
// Each row starts at rowStart and each subsequent circle is offset to
// the right by two times the circle diameter.
fields.add(new Field(0, rowStart.x + circle*DIAMETER*2, rowStart.y));
}
// Each subsequent row starts a little down and to the left of the previous.
rowStart.x -= DIAMETER;
rowStart.y += DIAMETER;
}
Remember to only use this as reference for fixing your own code if this is homework.