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();
}
Related
I'm working on a Guessing Game that will uses arrays to store both the names of all the players and their guesses. I'm fairly new to arrays, so my plan to get user input into the array was to get them to enter the amount of people playing, set that up as a variable and then use a loop to keep asking for names until I reached the necessary amount of names for the stated number of players. However, I am running into what probably is a very simple problem with the loop. Here's a small bit of my code thus far:
public class GuessGame {
int w = 0;
int[] Players = new int[100];
String[] PlayerNames = new String[100];
String numStart = JOptionPane.showInputDialog("How many players?");
int j = Integer.parseInt(numStart);
while (w <= j)
{
String Name = JOptionPane.showInputDialog("What is your name?");
PlayerNames[w] = Name;
w++;
}
The problem is, I'm getting an error regarding the variables in my loop, w and j. The error statement says something to the effect of it cannot find the symbols for class w or class j. I don't intend for them to be classes, and I've run similar code in other projects without a hitch, so I really don't know what's going wrong here. I'm sure it's something stupidly simple, but *'ve been stuck at this wall for some time now and can't really progress until I get this sorted. This is part of a project with three separate classes. The class posted here, a Player class, and a Tester class, which is my main method. I had the whole thing working in a more simplified form earlier, but now I need to adjust it for actual player input and the arrays. Regardless, the tester class is supposed to be my main class. I am using Netbeans if it matters. Thank you. Here are the other two classes for reference:
package GuessGame;
public class GameLauncher {
public static void main(String[] args) {
GuessGame game = new GuessGame();
game.startGame();
}
}
and
package GuessGame;
import java.util.Random;
public class Player {
int number = 0; //where guess goes
String name;
public void guess() {
Random r = new Random();
number = 1 + r.nextInt(21);
System.out.println("I'm guessing " + number);
}
}
All your code needs to be in a method. You cannot have anything except variable declarations at the class level. Move all this into a method, for example public static void main(String[] args) main method.
public class GuessGame {
public static void main (String[] args)
{
int w = 0;
int[] Players = new int[100];
String[] PlayerNames = new String[100];
String numStart = JOptionPane.showInputDialog("How many players?");
int j = Integer.parseInt(numStart);
while (w <= j)
{
String Name = JOptionPane.showInputDialog("What is your name?");
PlayerNames[w] = Name;
w++;
}
}
}
public class GuessGame {
public void getPlayerName()
{
int w = 0;
int[] Players = new int[100];
String[] PlayerNames = new String[100];
String numStart = JOptionPane.showInputDialog("How many players?");
int j = Integer.parseInt(numStart);
while (w <= j)
{
String Name = JOptionPane.showInputDialog("What is your name?");
PlayerNames[w] = Name;
w++;
}
}
public static void main (String[] args)
{
GuessGame gg = new GuessGame();
g.getPlayerName();
}}
You can put in the methos as well and execute in the main method. But, if you declaring any variable inside the method (local variable), the variable must be initialised. Refer here for more details.
public class GuessGame
{
static int w = 0;
int[] Players = new int[100];
static String[] PlayerNames = new String[100];
public static void main(String[] args) {
// TODO Auto-generated method stub
String numStart = JOptionPane.showInputDialog("How many players?");
int j = Integer.parseInt(numStart);
while (w <= j)
{
String Name = JOptionPane.showInputDialog("What is your name?");
PlayerNames[w] = Name;
w++;
}
}
}
Everything should be in a method except variables.Class is template for variables and methods !!
I need to write a program to solve the eight queens problem and I have no idea how to do it, but I have already started with the multidimensional array. The thing is that I don't know how to call a constructor from the main class, just to check if the array was constructed properly, or how to call it from a method. Can anybody help, please? This is the code, it returns null.
import javax.swing.JOptionPane;
public class Eightqueens
{
private static int[][] board;
public static void main(String[] args)
{
JOptionPane.showMessageDialog(null,board);
}
public Eightqueens (int size)
{
size = 8;
board = new int[size][size];
int row;
int col;
for (row = 0; row < size; row++)
for (col = 0; col < size; col++)
board[row][col] = 0;
}
}
You are supposed to use the value passed to the constructor, not overwrite it :
...
private int[][] board;
...
public Eightqueens (int size)
{
size = 8; // remove this
...
}
public int[][] getBoard()
{
return board;
}
public static void main(String[] args)
{
Eightqueens equeens = new Eightqueens (8); // create an instance
JOptionPane.showMessageDialog(null,equeens.getBoard()); // use accessor to get
// board
}
In addition, it doesn't make sense to initialize a static variable (board) in the constructor, since each new instance you create would overwrite its value. I'd change it to non-static, and then you can get it from your instance by using an accessor method (equeens.getBoard()).
To call your constructor you must 'construct' a new object.
Eightqueens obj = new Eightqueens(5);
just when you instantiate your object of class with new keyword , you call your constructor.
like this :
public static void main(String[] args) {
Eightqueens eq = new Eightqueens(5);
}
You can start by calling your constructor by making a new instance of Eightqueens
int size = 1; // anything
new Eightqueens(size);
This code does not return null, it does not return anything. You never call your constructor :
public static void main(String[] args) {
Eightqueens eq = new Eightqueens(5);
}
You can't call your constructor again. It only runs at the start of the code.
You can however, create a new instance of it to run it again.
The Dialog Box is empty because the value of board is nothing, which is because it has not been initialized. The board get a value in the constructor method. So you have to call the constructor method before you show the dialog box.
public static void main(String[] args)
{
Eightqueens eq = new Eightqueens(8);
JOptionPane.showMessageDialog(null,board);
}
Also, in the constructor method, you are overwriting the value of size given by you earlier. Thus, there is practically no need to supply the variable to the method. So, either you remove the line:
size = 8;
or, change the constructor method to not input the value, like this:
public Eightqueens ()
{
int size = 8;
board = new int[size][size];
int row;
int col;
for (row = 0; row < size; row++)
for (col = 0; col < size; col++)
board[row][col] = 0;
}
I'm not very good at programming, but I am obliged to write a program that calculates the product of two matrices by two methods :
The first method in a direct way.
The second using Threads so that the computation time is minimal.
I wrote this program for the first method :
Matrix.java
public class Matrix {
public int [][] M;
public int line,col;
static int [][]MProd=null;
//Constructeur
public Matrix (int [][] M,int line,int col) {
this.M=M;
this.col=col;
this.line=line;
for ( int i=0;i<this.line;i++){
for (int j=0;j<this.col;j++)
{
M[i][j]=(int)(Math.random()*100);}}
}
static int [][] prod(Matrix Mat1, Matrix Mat2 ){
for (int j=0;j<Mat2.col;j++){
for (int i=0;i<Mat1.col;i++){
for (int k=0;k<Mat1.line;k++){
MProd[k][j] += Mat1.M[k][i]*Mat2.M[i][j];
}}}
return MProd ;
}}
Main.java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int [][] M = null,N = null;
int line1,line2,col1,col2;
int [][] P=null;
Scanner scanner = new Scanner(System.in);
System.out.println("enter the line number of the first matrix");
line1=scanner.nextInt();
System.out.println("enter the number of columns of the first matrix");
col1=scanner.nextInt();
Matrix Mat= new Matrix (M,line1,col1);
System.out.println("enter the line number of the 2nd matrix");
line2=scanner.nextInt();
System.out.println("enter the number of columns of the 2nd matrix");
col2=scanner.nextInt();
Matrix Mat1= new Matrix (N,line2,col2);
if (col1==line2)
{
P=Matrix.prod(Mat,Mat1) ;
System.out.println("matrix product :");
for (int i=0;i<Mat.line;i++)
{
for (int j=0;j<Mat1.col; j++)
System.out.print( + P[i][j]+" ");
System.out.println();
}}
else {
System.out.println("the matrices product is impossible");
}
}}
when I run the program it shows me :
Exception in thread "main" java.lang.NullPointerException
at Matrice.(Matrice.java:18)
at Main.main(Main.java:15)
Can someone help me to correct this program, and shows me how to write this program with Threads ?
Your NullPointerException is due to this:
public static void main(String[] args) {
int [][] M = null,N = null; // all declared null
// ...
Matrix Mat= new Matrix (M,line1,col1); // here you use a null value, M
// ...
Matrix Mat1= new Matrix (N,line2,col2); // and same here, N is null
When you call, M[i][j]=(int)(Math.random()*100); in your Matrix class, M is null so this will fail. You must first create a Matrix, your 2D array, before you can use it.
Edit
You ask:
Can you explain me more.
You're passing a null reference into your Matrix constructor and then trying to use it as a variable. You should pass a non-null 2D array instead:
int[][] myArray = new int[x][y]; // where x and y are appropriate numbers
Matrix Mat= new Matrix (myArray, line1, col1);
Also, please study and use standard Java Coding Conventions (please see link) including:
All class, enum and interface names begin with an uppercase letter.
All method and variable names begin with a lowercase letter.
Learn to use judicious use of white space including a space between parameters.
Do this and folks will be better able to read and understand your code and then be able to give you better help.
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.
I think the constructor is logically correct, I just can't figure out how to call it in the main ! :) Can anyone help please ? If someone would just have a quick look over my code it would be nice :) Thanks a lot !
Also, I am using arrayLists in this implementation and I have to do it this way so I don't wish to change it, even though it is far more easily implemented using only arrays.
import java.util.*;
public class PrimeNumberss {
public static void main(String args []){
PrimeNumberss PrimeNumbers = new PrimeNumberss(10);
}
public PrimeNumberss (int initialCapacity) {
ArrayList<Integer> listOfPrimeNumbers = new ArrayList<Integer>(initialCapacity);
long numberOfPrimes = 0; //Initialises variable numberOfPrimes to 0
int start = 2;
boolean[] isPrimeNumber = new boolean[initialCapacity + 1];
for (int i=0;i==initialCapacity;i++) {//setting all values in array of booleans to true
isPrimeNumber[i] = true;
}
while (start != initialCapacity)
{
if (isPrimeNumber[start])
{
listOfPrimeNumbers.add(start);
//add to array list
numberOfPrimes++;
for (int i = start; start < initialCapacity; i+=start)
{
isPrimeNumber[i] = false;
}
}
start++;
}
}
}
Your algorithm is not correct; you will only find the primes less than N (your initial capacity), not the first N primes.
If you're going to store each prime, you should store them in a class variable not a variable local to the constructor. You won't be able to access them outside the constructor if you do.
You should expose the list using a getter method to provide access to them.
You're not printing anything in the constructor.
i==initialCapacity is clearly wrong.
Everything important is there, its small changes. Right now you are getting primes less than N, so if you want to change it to first N primes that's going to be a real functional difference. For now lets just make N=50 so you'll get well over 10 primes.
public class PrimeNumberss {
private List listOfPrimeNumbers; //add a member variable for the ArrayList
public static void main(String args []){
PrimeNumberss PrimeNumbers = new PrimeNumberss(50);
PrimeNumbers.print(); //use our new print method
}
public PrimeNumberss (int initialCapacity) {
listOfPrimeNumbers = new ArrayList<Integer>(initialCapacity/2); //initialCapacity/2 is an easy (if not tight) upper bound
long numberOfPrimes = 0; //Initialises variable numberOfPrimes to 0
int start = 2;
boolean[] isPrimeNumber = new boolean[initialCapacity + 1];
for (int i=0;i==initialCapacity;i++) {//setting all values in array of booleans to true
isPrimeNumber[i] = true;
}
//.... complete the constructor method as you have it. honestly, i didnt even read it all
public void print() //add this printout function
{
int i = 1;
it = listOfPrimeNumbers.listIterator();
while (it.hasNext())
{
System.out.println("the " + i + "th prime is: " + it.next());
i++;
}
//or just System.out.println(listOfPrimeNumbers);, letting ArrayList's toString do the work. i think it will be in [a,b,c,..,z] format
}
public List getPrimes() {return listOfPrimeNumbers;} //a simple getter isnt a bad idea either, even though we arent using it yet
}
On a side note, you could probably d oa little better with the naming (PrimeNumberss and PrimeNumbers??), but I didnt change any of that. Also, intiialCapacity does not reflect what it really means. Maybe something along the lines of 'top'.