Solving the 8 queens - java

What I am trying to do is solving the 8 queen problem to produce 1 solution. I am trying to do this using BFS. Below is what I have done so far. I think all my functions/methods are all correct apart from the final method() which I can't get to work. If I compile and run the following code, I get a NullPointerException. Wondering how I can overcome this problem and get it to work.
public class Queens
{
//Number of rows or columns
public int[][] board; // creating a two dimentional array
public int Queen = 1;
//Indicate an empty square
public boolean Conflict(int row, int col)
{
int[ ][ ]board = new int[8][8];
int row1;
int col1;
boolean flg = false;
row1 = row;
col1 = col;
// check right
while(row1<8)
{
if(board[row1][col1]==1)
{
row1++;
}
}
//check left
while(row1>=0)
{
if(board[row1][col1]==1)
{
row1--;
}
}
// check down
while(col1<8)
{
if(board[row1][col1]==1)
{
col1++;
}
}
// check up
while(col1>1)
{
if (board[row1][col1]==1)
{
col1--;
}
}
//dia-down-right
while(row1<8 && col1<8){
if(board[row1][col1]==1)
{
row1++;
col1++;
}
}
//dia-down-left
while(row1>=0 && col1<8){
if(board[row1][col1]==1)
row1--;
col1++;
}
//dia-up-left
while(row1>=0 && col1>=0){
if(board[row1][col1]==1)
row1--;
col1--;
}
//dia-up-right
while(row1<8 && col1>=0){
if(board[row1][col1]==1)
row1++;
col1--;
}
return flg;
}
public void disp()
{
int i,j;
for(i=0;i<8;i++)
{
for(j=0;j<8;j++)
{
System.out.println(board[j][i]);
}
//System.out.println(board[j][i]);
}
}
public void init()
{
int i,j;
for(i=0;i<8;i++)
{
for(j=0;j<8;j++)
{
board[i][j] = 0;
}
}
}
public void placeQueen(int x,int y)
{
board[x][y]= Queen;
Queen++;
}
public void method()
{
int x,y;
int initx=0;
int inity=0;
Queen=0;
init();
placeQueen(initx,inity);
y=0;
while(y<8)
{
x=0;
while(x<8)
{
if(!Conflict(x,y))
{
placeQueen(x,y);
x++;
}
}
y++;
}
if(Queen<8){
if(initx+1<8)
{
initx++;
disp();
}
else
{
initx=0;
if(inity+1<8)
{
inity++;
}
else{
disp();
}
}
}
}
public static void main(String[] args)
{
Queens Main = new Queens();
Main.method();
}
}

You need to initialize the board on line 5, otherwise when called in init board:
board[i][j] = 0;
board[i][j] is null
public class Queens
{
//Number of rows or columns
public int[][] board = new int[8][8]; // creating a two dimentional array
public int Queen = 1;

Related

RPG game code error [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I keep getting this error in my code. Can someone fix it and how is the code written? Can it be improved by maybe using setters and getters only?
Exception in thread "main" java.lang.NullPointerException
at Player.attack(Player.java:72)
at Main.main(Main.java:15)
My code:
Player.java
public class Player {
String name;
String race;
int hp;
int power;
int armour;
Weapon weapon;
public Player (String n, String r, int h, int p, int a) {
name = n;
race =r;
hp = h;
power = p;
armour = a;
}
public void setName (String n) {
name = n;
}
public String getName() {
return name;
}
public void setRace (String r) {
race = r;
}
public String getRace() {
return race;
}
public void setHP (int h) {
hp = h;
}
public int getHP() {
return hp;
}
public void setPower (int p) {
power = p;
}
public int getPower() {
return power;
}
public void setArmour (int a) {
armour = a;
}
public int getArmour() {
return armour;
}
public boolean dead() {
return hp <= 0;
}
public boolean equip(Weapon weapon) {
this.weapon = weapon;
return true;
}
public boolean receiveDamage(int i) {
if ((hp - i) > 0) {
hp = hp - i;
return true;
}
hp = 0;
return false;
}
public boolean attack(Player player) {
return player.receiveDamage(weapon.useWeapon());
}
}
Main.java
public class Main {
public static void main(String args[]) {
Player Mensch = new Player("Mensch", "Mensch", 85, 12, 10);
Player Ork = new Player("Shrek", "Ork", 50, 14, 6);
Weapon MenschW = new Weapon("mächtiges Schwert", 15, 100);
Weapon OrkW = new Weapon("große Axt", 7, 100);
Mensch.equip(Mensch.weapon);
Ork.equip(Ork.weapon);
while (!Mensch.dead() && !Ork.dead() ) { //Alternativ: for (player hp >=0)
System.out.println("Mensch gegen Ork " + Mensch.attack(Ork));
if (Mensch.dead() || Ork.dead()) {
break;
}
System.out.println("Mensch gegen Ork " + Ork.attack(Mensch));
}
System.out.println("Ork ist tot: " + Ork.dead());
System.out.println("Mensch ist tot: " + Mensch.dead());
}
}
Weapon.java
import java.util.concurrent.ThreadLocalRandom;
public class Weapon {
String name;
int damage;
int hp;
public Weapon(String string, int d, int hp) {
// TODO Auto-generated constructor stub
}
public void setName (String n) {
name = n;
}
public String getName() {
return name;
}
public void setDamage (int d) {
damage = d;
}
public int getDamage() {
return damage;
}
public void setWHP (int h) {
hp = h;
}
public int getWHP() {
return hp;
}
public int useWeapon() {
if
(broken())
return 0;
hp = hp - 5;
return (damage / 2) + random();
}
private int random() {
return ThreadLocalRandom.current().nextInt(1, damage + 1);
}
private boolean broken() {
return hp <= 0;
}
}
I know its a lot of code but I keep getting the same error, also I'm quite new to java so I would appreciate some tips or suggestions to make my code better or more failsave. The code doesn't do much yet but it will (hopefully) be a simple game soon in which two characters fight eachother with some calculations on damageoutput of each player. In this case a Human and Ork. Feel free to try it out
Change
Mensch.equip(Mensch.weapon); // Mensch.weapon is not initialized in constructor so it is null.
Ork.equip(Ork.weapon); // Ork.weapon is not initialized in constructor so it is null as well.
To
// Use your newly created weapons in the main instead.
Mensch.equip(MenschW );
Ork.equip(OrkW);

StackOverFlowError when looping through options

I'm working on an exercise and I'm running into something. The following code gives me a stackoverflow error, but I have no idea why because my code should stop.
class Options {
private int amount;
private ArrayList<Integer> pieces;
public void execute() {
pieces = new ArrayList<Integer>();
pieces.add(5);
pieces.add(2);
pieces.add(3);
amount = pieces.size();
combinations(new StringBuilder());
}
public void combinations(StringBuilder current) {
if(current.length() == pieces.size()) {
System.out.println(current.toString());
return;
}
for(int i = 0; i < amount; i++) {
current.append(pieces.get(i));
combinations(current);
}
}
}
It only prints the first output (555).
Thanks.
Add a return to end your recursion
public void combinations(StringBuilder current) {
if(current.length() == pieces.size()) {
System.out.println(current.toString());
return; // <-- like so.
}
for(int i = 0; i < amount; i++) {
current.append(pieces.get(i));
combinations(current);
}
}
or put the loop in an else like
public void combinations(StringBuilder current) {
if(current.length() == pieces.size()) {
System.out.println(current.toString());
} else {
for(int i = 0; i < amount; i++) {
current.append(pieces.get(i));
combinations(current);
}
}
}
Edit
static class Options {
private List<Integer> pieces;
public void execute() {
pieces = new ArrayList<>();
pieces.add(5);
pieces.add(2);
pieces.add(3);
combinations(new StringBuilder());
}
public void combinations(StringBuilder current) {
if (current.length() == pieces.size()) {
System.out.println(current.toString());
} else {
for (int i = current.length(); i < pieces.size(); i++) {
current.append(pieces.get(i));
combinations(current);
}
}
}
}
public static void main(String[] args) {
Options o = new Options();
o.execute();
System.out.println(o.pieces);
}
Output is
523
[5, 2, 3]

TicTacToe game, no output

In this code I want to create a 3x3 board game, but nothing appears on the screen..(code compiles correctly but doesn't show output)
I think the problem is in the main method... Can't figure it out... Please help!
package games;
import games.board.*;
public class BoardGameTester {
/**
* #param args
*/
private static Board gb;
public static void main(String[] args) {
// TODO Auto-generated method stub
gb = new Board(3, 3);
}
}
Here is a board.java:
package games.board;
public class Board {
private Cell[][] cells;
public Board(int rows, int columns) {
cells = new Cell[rows][columns];
for( int r = 0; r < cells[0].length; r++ ) {
for (int c = 0; c < cells[1].length; c++) {
cells[r][c] = new Cell(r,c);
}
}
}
public void setCell(Mark mark, int row, int column) throws
IllegalArgumentException {
if (cells[row][column].getContent() == Mark.EMPTY)
cells[row][column].setContent(mark);
else throw new IllegalArgumentException("Player already there!");
}
public Cell getCell(int row, int column) {
return cells[row][column];
}
public String toString() {
StringBuilder str = new StringBuilder();
for( int r = 0; r < cells.length; r++ ) {
str.append("|");
for (int c = 0; c < cells[r].length; c++) {
switch(cells[r][c].getContent()) {
case NOUGHT:
str.append("O");
break;
case CROSS:
str.append("X");
break;
case YELLOW:
str.append("Y");
break;
case RED:
str.append("R");
break;
case BLUE:
str.append("B");
break;
case GREEN:
str.append("G");
break;
case MAGENTA:
str.append("M");
break;
case ORANGE:
str.append("M");
break;
default: //Empty
str.append("");
}
str.append("|");
}
str.append("\n");
}
return str.toString();
}
}
Here is a cell.java
package games.board;
public class Cell {
private Mark content;
private int row, column;
public Cell(int row, int column) {
this.row = row;
this.column = column;
content = Mark.EMPTY;
}
public Mark getContent() { return content; }
public void setContent(Mark content) { this.content = content; }
public int getRow() { return row; }
public int getColumn() { return column; }
}
Here is mark.java
package games.board;
public enum Mark {
EMPTY, NOUGHT, CROSS, YELLOW, RED, BLUE, GREEN, MAGENTA, ORANGE
}
Here is outcome.java
package games.board;
public enum Outcome {
PLAYER1_WIN, PLAYER2_WIN, CONTINUE, TIE
}
here is player.java
package games.board;
public enum Player {
FIRST,SECOND
}
you are not genereting any output
to print the board to the console try:
public static void main(String[] args) {
// TODO Auto-generated method stub
gb = new Board(3, 3);
System.out.println(gb);
}
it will invoke the gb.toString() methode
ps: it's maybe easier to read if you use str.append("\n") instead of str.append("|")
Try this :
public static void main(String[] args) {
// TODO Auto-generated method stub
gb = new Board(3, 3);
System.out.println(gb.toString());
}

Can someone please tell me why my Game of Life code wont work?

There are no errors showing up in eclipse, but when I go to run the code, nothing happens in the application. It is broken up into three classes. The first class contains the if statements. I am wondering if my issue lies here.
package course.infsci0017.lab04;
import java.util.Scanner;
import javax.swing.JFrame;
public class GameOfLife {
public static void main(String[] args) {
int testCase = 1;
JFrame frame = new JFrame();
frame.setSize(500, 500);
frame.setTitle("Conway's Game of Life");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Cell[][] universe = new Cell[100][100];
for (int x = 0; x < universe.length-1; x++) {
for (int y = 0; y < universe[x].length-1; y++) {
universe[x][y] = new Cell();
}
}
if (testCase == 1) {
universe[3][2].calculateNext(3);
universe[3][2].updateCurrent();
universe[3][3].calculateNext(3);
universe[3][3].updateCurrent();
universe[3][4].calculateNext(3);
universe[3][4].updateCurrent();
} else if (testCase == 2) {
universe[49][50].calculateNext(3);
universe[49][50].updateCurrent();
universe[49][51].calculateNext(3);
universe[49][51].updateCurrent();
universe[50][49].calculateNext(3);
universe[50][49].updateCurrent();
universe[50][50].calculateNext(3);
universe[50][50].updateCurrent();
universe[51][50].calculateNext(3);
universe[51][50].updateCurrent();
} else {
}
UniverseComponent component = new UniverseComponent(universe);
frame.add(component);
frame.setVisible(true);
Scanner in = new Scanner(System.in);
String input = in.nextLine();
while (input.length() == 0) {
int neighborCount = 0;
for (int x=1; x<universe.length-2; x++) {
for (int y=1; y<universe[x].length-2; y++) {
neighborCount = 0;
if (universe[x-1][y-1].isAlive()) {
neighborCount++;
}
if (universe[x-1][y].isAlive()) {
neighborCount++;
}
if (universe[x-1][y+1].isAlive()) {
neighborCount++;
}
if (universe[x][y-1].isAlive()) {
neighborCount++;
}
if (universe[x][y+1].isAlive()) {
neighborCount++;
}
if (universe[x+1][y-1].isAlive()) {
neighborCount++;
}
if (universe[x+1][y].isAlive()) {
neighborCount++;
}
if (universe[x+1][y+1].isAlive()) {
neighborCount++;
}
universe[x][y].calculateNext(neighborCount);
}
}
for (int x=1; x<universe.length-2; x++) {
for (int y=1; y<universe[x].length-2; y++) {
universe[x][y].updateCurrent();
}
}
component.repaint();
input = in.nextLine();
}
in.close();
}
}
Class 2
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JComponent;
public class UniverseComponent extends JComponent {
private Cell[][] universe;
public UniverseComponent(Cell[][] universe) {
super();
this.universe = universe;
}
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D)g;
for (int x=0; x<universe.length-1; x++) {
for (int y=0; y<universe[x].length-1; y++) {
if (universe[x][y].isAlive()) {
g2.fillRect(x*5, y*5, 4, 4);
}
}
}
}
}
Class 3
public class Cell {
private boolean current;
private boolean next;
public Cell() {
current = false;
next = false;
}
public Cell(int neighborCount) {
calculateNext(neighborCount);
updateCurrent();
}
public void calculateNext(int neighborCount) {
if (current) {
if ((neighborCount < 2) || (neighborCount > 3)) {
next = false;
} else {
next = true;
}
} else {
if (neighborCount == 3) {
next = true;
} else {
next = false;
}
}
}
public void updateCurrent() {
current = next;
}
public boolean isAlive() {
return current;
}
}
If any one has any idea what how to fix this please let me know. Feel free to copy and paste code if necessary. It will not let me post an image because i do not have enough reputation. Apologies
Your while loop says
while (input.length() == 0)
But if you type anything into the input at all, it will not be equal to zero, so the loop will not be executed and your program will exit.
The program seems to be designed to only allow the user to hit 'enter' without typing any words at the console. That is, the loop will be executed if you type nothing but enter, otherwise the program will exit.
This is obviously not your own code, since it doesn't appear to have a bug after all but your usage of it is incorrect. Please be more honest with your questions (and I hope you haven't been plagiarising).

Problem Adding incremented class member variable to arraylist inside loop

Trying to add an incremented class member variable 'nNodeIndex' to arraylist, but at the end of the loop all the values stored are identical to the last iteration increment??
Class with member variable:
import java.util.ArrayList;
public class Graph {
private static ArrayList<GraphNode> Nodes = new ArrayList<GraphNode>();
private static ArrayList<GraphEdge> Edges = new ArrayList<GraphEdge>();
private static boolean diGraph;
private static int nNodeIndex;
private boolean uniqueEdge(int from, int to)
{
for(int i=0; i< Edges.size(); i++){
if(Edges.get(i).from() == from && Edges.get(i).to() == to)
return false;
}
return true;
}
private void removeInvalidEdges(int nodeIndex)
{
for(int i=0; i<Edges.size(); i++)
{
if(Edges.get(i).from() == nodeIndex)
Edges.remove(i);
if(Edges.get(i).to() == nodeIndex)
Edges.remove(i);
}
}
Graph(boolean directionalGraph)
{
diGraph = directionalGraph;
nNodeIndex = 1;
}
public GraphNode getNode(int nodeIndex)
{
return Nodes.get(nodeIndex);
}
public int getIndexByVector(int x, int y)
{
for(int i=0; i<Nodes.size(); i++)
{
if(Nodes.get(i).x() == x && Nodes.get(i).y() == y)
return i;
}
return -1;
}
public int nextFreeNodeIndex(){ return nNodeIndex; }
public void addNode(GraphNode node)
{
if(Nodes.size() > 0)
Nodes.add(node.index()-1, node);
else
Nodes.add(node);
nNodeIndex++;
}
public void removeNode(int index)
{
Nodes.get(index).setIndex(-1);
removeInvalidEdges(index);
}
public void addEdge(GraphEdge edge)
{
if(uniqueEdge(edge.from(), edge.to()))
Edges.add(edge);
if(!diGraph)
{
if(uniqueEdge(edge.to(), edge.from()))
Edges.add(new GraphEdge(edge.to(), edge.from()));
}
}
public void removeEdge(GraphEdge edge)
{
for(int i=0; i<Edges.size(); i++)
if(Edges.get(i).from() == edge.from() &&
Edges.get(i).to() == edge.to())
{
Edges.remove(i);
}
}
public int totalNodes(){ return Nodes.size(); }
public int totalEdges(){ return Edges.size(); }
public int nActiveNodes()
{
int count = 0;
for(int i=0; i<Nodes.size(); i++)
{
if(Nodes.get(i).index() != -1 )
count++;
}
return count;
}
public void reset()
{
nNodeIndex = 1;
Nodes.clear();
Edges.clear();
}
}
Use within main class:
for(int row = 1; row <= boardWidth; row++){
for(int col = 1; col <= boardHeight; col++){
graph.addNode(new GraphNode(graph.nextFreeNodeIndex(), row, col));
}
}
Graph Node class:
public class GraphNode extends Square {
private static int indexNum;
GraphNode(int n, int x, int y)
{
super(x,y);
indexNum = n;
}
public int index(){ return indexNum; }
public void setIndex(int index){ indexNum = index; }
}
Do you need to show us the GraphNode class? I wonder if the node index held by it (set by the first parameter passed in its constructor) is a static variable.

Categories