I am new to Java and I'm grateful if anyone could help with the below. I am trying to make a scorekeeper for my chessboard. At the moment, the score will go back to zero everytime. How would I be able to save the previous score and add it every move? Thanks!
public static int scoreKeeper(Chessmen[][] chessboard, int X, int Y, int X1, int Y1, int currentNumber, int totalNumber){
AbstractPiece knight = new Knight();
AbstractPiece bishop = new Bishop();
AbstractPiece pawn = new Pawn();
AbstractPiece king = new King();
AbstractPiece queen = new Queen();
AbstractPiece rook = new Rook();
if ((chessboard[Y][X] == Chessmen.WHITE_KNIGHT) ||
(chessboard[Y][X] == Chessmen.BLACK_KNIGHT)){
currentNumber = currentNumber+totalNumber+knight.relativeValue();
return currentNumber;
}else return totalNumber;
}
The main problem you have is that you are passing the value of currentNumber as a parameter
that means it will not change outside this method
this Example will illustrate my point
public class Test{
public static void main (String[] args){
int a = 0 ;
changeValue(a);
System.out.print(a);
}
public static void changeValue(int a){
a=20;
}
}
the output will be always 0 .
you can solve it by writing the methods getValueOfCurrentNumber() and getValueOfTotalNumbe()
to get the values [currentNumber and totalNumbe] instead of taking them as parameters .
The easiest solution is to store your score as a class data member:
class Game {
static int score;
public static int updateScore(... some inputs...) {
if(some condition is true) {
score = score + whatever you want to add;
}
}
}
The class retains the value of "score" between method calls.
I suspect that you have a bad abstraction. I think you want a Chessboard to hide the 2D array of Chessmen. Let it keep the current score as a data member. Provide methods to select and move pieces appropriately.
I can see its constructor instantiating a Chessboard. It would set each of the pieces at their appropriate starting positions. Then each Player would take turns moving.
Not a trivial problem.
Related
I am very new to Java, and I'm having a difficult time figuring out how to take arguments from the command prompt and pass them around in my code. I am able to get them into the main method of my code, but I'd rather have them in the Chessboard class. There is a public static int n that is hard coded, but I would like it to be whatever I send in as arguments. I'll later be taking an initial position for a queen's placement, so I'm hoping the process will be similar; if I get help with this, hopefully I can use the same technique for that.
public class Chessboard {
public static void main(String[] args) {
System.out.println("Hello World");
Chessboard board = new Chessboard(); //creates a Chessboard object
board.start();
}
public static int n = 8;
private static int board[][]; //this is the Chessboard array
private int numQueens; //this is the number of queens on the board
public Chessboard(){
numQueens = 0; //initialized to zero, no queens on board to start yet
board = new int[n][n]; //nxn 2D array of zeros
for (int j = 0; j < n; j++)
{
for (int k = 0; k < n; k++)
{
board[j][k] = 0; //redundant, but I need to learn how to
} //initialize. this manually puts zeros into
} //the array
}
...and the code continues from here, but I don't think it's necessary. If it is, I'm happy to upload it.
Thank you for your time.
Here's what I'd do.
public static void main(String[] args) {
try {
int firstArg = Integer.parseInt(args[0]);
Chessboard board = new Chessboard(firstArg);
// Do some stuff with the chessboard here.
}
catch(NumberFormatException e) {
System.out.println("That's not a number");
}
}
This looks at the first command line argument and tries to convert it to an int. If it succeeds, it passes that int to the constructor of Chessboard to make an object for you to use.
This snippet also shows how you can provide code that runs if the first command line argument isn't actually a number.
Notice that the main method is already in your Chessboard class. If you want to leave your n variable as static, you can just do this in the main method.
n = Integer.parseInt(args[0]);
If you make n an instance variable instead of having it be static, then the answer that David Wallace gave will point you in the right direction.
In your Chessboard Class create an
private String[] args;
Then add an setter to Chessboard like:
public void setArgs(String[] args{
this.args = args;
}
Then put something like this in your main:
public static void main(String[] args) {
Chessboard board = new Chessboard();
board.setArgs(args);
board.start();
}
For example, if this is my class...
public class Person {
private double height; //Height in inches
//constructors
public Person(double newHeight) {height = newHeight;}
public Person() {}
//Getter
public double getHeight() {return height;}
//Setter
public void setHeight(double newHeight) {height = newHeight;}
}
and then this is my driver...
import javax.swing.JOptionPane;
class Myclass {
public static void main{String[] args) {
String userInput;
int arraylen;
Person bob = new Person ();
double[] myarray;
userInput = JOptionPane.showInputDialog("How many heights do you have
to list?");
arraylen = Integer.parseInt(userInput);
myarray = new double[arraylen];
for(int i=0;i<myarray.length;i++) {
userInput = JOptionPane.showInputDialog("What is the next height?");
bob.setHeight(Double.parseDouble(userInput));
// I need something here to put that attribute value into the array.
}
}
}
So at this point I have a value in the height attribute and I need to figure out how to move that into an array. I'm sure putting user input into an attribute to just then move it to an array probably isn't the best way to do this, but it's for school, so it's what I need to figure out. Please share any suggestions of better ways to do it though. However, I'm mainly concerned with how to do it like this.
What you seem to want to do, setting the height of bob to a value, and then setting the entry in an array to the height of bob, can be done by adding the line:
myarray[i] = bob.getHeight();
to the end of your for loop.
Alright so I am doing an exercise where I have an object that contains scores for 3 tests.
I then have a set-function that takes 2 arguments, the test number and the score you set to it.
Right now my problem is that I do not know how to make the test number argument work correctly.
The code works if I do test1 = score, but when I put student1.test1 in the set argument, for some reason it does not register.
I hope you can point me in the right direction, I would be really grateful!
I have a main class and a student class:
public class Main {
public static void main(String[] args) {
Student student1 = new Student();
student1.setTestScore(student1.test1, 50);
System.out.print(student1.test1);
}
}
public class Student {
int test1;
int test2 = 0;
int test3;
Student() {
int test1 = 0;
int test2 = 0;
int test3 = 0;
}
public void setTestScore(int testNumber, int score){
testNumber = score;
}
}
Java is a pass by value language, so when you pass student1.test1 to student1.setTestScore, you are passing a copy of that member. You are not passing a reference to the member. Therefore the method can't change the member's value.
Even if the language allowed such modification, it would be a bad idea in terms of object oriented programming, since you normally make members private and don't access them directly from outside the class.
A possible alternative is to use an array :
public class Student {
int[] test = new int[3];
...
public void setTestScore(int testNumber, int score){
if (testNumber >= 0 && testNumber < test.length)
test[testNumber]=score;
}
...
}
and you'd call the method like this :
student1.setTestScore(0, 50); // note that valid test numbers would be 0,1 and 2
import java.awt.*;
import hsa.Console;
public class Game{
static Console c;
public static void Wait (int time){
try{
Thread.sleep (time);
}
catch (InterruptedException e){
}
}
public static class Tile{
public int x,y,stack;
public Tile(){
x = 0;
y = 0;
stack = 0;
}
public Tile(int xco, int yco, int stacknum){
x = xco;
y = yco;
stack = stacknum;
}
public void draw(Tile tile){ //To draw the tile
if(stack>0){
c.setColor(Color.red);
c.fillRect(x*78+1+x,y*78+1+y,78,78); //Calculate coordinates
}
else{
c.setColor(Color.blue);
c.fillRect(x*78+1+x,y*78+1+y,78,78);
}
}
}
public static void main (String[] args){
c = new Console ();
for(int i=0;i<640;i+=79) c.drawLine(i,0,i,474);
for(int i=0;i<500;i+=79) c.drawLine(0,i,632,i);
//8x6 tiling
Tile[][] tile = new Tile[8][6];
for(int i=0;i<8;i++){
for(int j=0;j<6;j++){
tile[i][j] = new Tile();
tile[i][j].x = i;
tile[i][j].y = j; //Set x and y coordinates
tile[i][j].stack = 5;
}
}
Tile.draw(tile[0][0]);
}
}
Here I have a tile of 8x6 squares using a multidimensional array. I would think that the coordinates would correspond to the correct numbers, but for some reason the coordinates seem to copy the ones created before it. Could someone tell me why this is happening and how the code should be corrected? Btw I started java so I'm not completely used to object oriented programming :P
Your co-ordinates are declared as static:
public static int x,y,stack;
Fields that have the static modifier in their declaration are called static fields or class variables. They are associated with the class, rather than with any object. Every instance of the class shares a static class variable, which is in one fixed location in memory.
You should however remove the static modifier to have specific value for each object of Tile
Edit:
From your below comment and for your better understanding, to work with draw() function:
Approach 1: If we wish to have draw function to be static:
public static void draw(Tile tile){ //To draw the tile
if(stack>0){
c.setColor(Color.red);
c.fillRect(tile.x*78+1 + tile.x, tile.y*78+1+tile.y, 78, 78);
//Calculate coordinates
}
else{
c.setColor(Color.blue);
c.fillRect(tile.x*78+1 + tile.x, tile.y*78+1+tile.y, 78, 78);
}
}
You can call this function by Tile.draw(tile); where tile is an instance of Tile
Approach 2: If draw(Title tile) function is non static: you don't need to pass the tile instance at all:
public void draw(){ //To draw the tile
if(stack>0){
c.setColor(Color.red);
c.fillRect(tile.x*78+1 + tile.x, tile.y*78+1+tile.y, 78, 78);
//Calculate coordinates
}
else{
c.setColor(Color.blue);
c.fillRect(tile.x*78+1 + tile.x, tile.y*78+1+tile.y, 78, 78);
}
}
Then create an instance Tile title = new Title() and call title.draw()
You've marked x, y, z as static so all instances of your class use the same ones, just remove the static keyword
In Java I have a 2-dimensional array of objects but I can't access any of those array of objects in the object's class methods. What should I do?
Here's my class:
class GoPiece
{
final int boardSize = 19;
final int empty = 0;
final int black = 1;
final int white = 2;
int pieceType = empty;
int leftRight;
int downUp;
int turnPlayed;
boolean legal;
// GoPiece's Constructor with 3 parameters.
GoPiece(int blackOrWhite, int horizontalCoordinate, int verticalCoordinate)
{
pieceType = blackOrWhite;
leftRight = horizontalCoordinate;
downUp = verticalCoordinate;
if ((true));
}
// GoPiece's Constructor with 2 parameters.
GoPiece(int horizontalCoordinate, int verticalCoordinate)
{
pieceType = empty;
leftRight = horizontalCoordinate;
downUp = verticalCoordinate;
}
// GoPiece's Constructor with no parameters.
GoPiece()
{
leftRight = 0;
downUp = 0;
}
// Initialize an empty Go board full of GoPieces.
GoPiece[][] InitializeBoard()
{
GoPiece[][] intersection = new GoPiece[boardSize][boardSize];
for(int horizontal = 0; horizontal < boardSize; horizontal++)
{
for(int vertical = 0; vertical < boardSize; vertical++)
{
intersection[horizontal][vertical] = new GoPiece(horizontal,vertical);
}
}
return intersection;
}
// Make a piece a certain type: empty, black, or white.
public void SetType(int newType)
{
pieceType = newType;
}
public int GetType()
{
return pieceType;
}
public void CheckKill()
{
int foobar = this.GetType();
}
}
I can then use InitializeBoard() in another part of my program to create a two dimensional array of GoPieces... this works, but How do I access all of those pieces other than the one I'm referencing in the class GoPiece's member functions? I tried passing the whole array into one of GoPieces functions, but that didn't seem to work.
Go is an Ancient Chinese Board game. The CheckKill() method above is where I tried to access different parts of the array, but failed. Here I have some working dummy code.
Thank you.
You need to create a separate class to represent the board itself (including the current placement of pieces). The logic for creating a board, testing for a kill, etc., belong to the board, not to an individual piece.
Do you mean you want to call a method with the array like InitializeBoard.GetType(); Where InitializeBoard is a 2 Dimensional Array?
You can't do that. You Must Specify which GoPiece to get out of InitializeBoard. Example: InitializeBoard[0][0].GetType(); If you must call all methods, you can use a for loop to call each individually.