I wrote two classes. The main class runs the program. It asks for user input. Based on user input, the second class will print out a square. Each square will print out ---- for every number and | for every number for the walls.
For example, say that the user entered two. In that case, it will print out a square.
----- -----
| |
| |
----- -----
The problem is that I cant get the square the grow based on the user input.
This is the main class
import java.util.Scanner;
public class Assignment4
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
SquareBuilder square = new SquareBuilder(scan.nextInt());
System.out.print(square.toString());
square.changeSize(scan.nextInt());
System.out.print(square.toString());
square.changeSize(scan.nextInt());
System.out.print(square.toString());
square.changeSize(scan.nextInt());
System.out.print(square.toString());
square.changeSize(scan.nextInt());
System.out.print(square.toString());
}
}
public class SquareBuilder
{
final private int LENGTH_RATIO = 4;
final private String CEILING_FLOOR = "----";
private int size;
private int spaces;
private String square;
public SquareBuilder(int size)
{
this.size = size;
constructSquare();
}
private void spaces()
{
spaces = LENGTH_RATIO * size - 2;
}
private void ceilingAndFloor()
{
square += "\n";
for (int i = 0; i < size; ++i)
{
square += CEILING_FLOOR;
}
}
private void walls()
{
for (int i = 0; i < size; ++i )
{
square +="\n|";
for (int j = 0; j < spaces; ++j)
{
square +=" ";
}
square +="|";
}
}
private void constructSquare()
{
spaces ();
square = "";
ceilingAndFloor();
walls();
ceilingAndFloor();
}
public int area()
{
return size * size;
}
public void changeSize(int size)
{
this.size = size;
}
public String toString()
{
String retVal = square;
retVal += "\nSize: " + size + " Area: " + area();
return retVal;
}
}
You're not even changing the part of your square that renders.
I think you want to invoke your constructSquare() method from your changeSize() method, or at least call constructSquare() before you print it again
put the constructSquare() in the changeSize function.
required changes:
public SquareBuilder(int size)
{
changeSize( size);
// constructSquare();
}
public void changeSize(int size)
{
this.size = size;
constructSquare();
}
Related
I need to create an instance variable called ocean, using the data type Coordinate[][]
Where do I specify that the data type of the elements in the array should be type char?
As per the instructions, I can't add input parameters to the constructor in the Coordinate class.
Any help would be appreciated :)
package battleshipmodel;
// Player class contains a default implementation for a player.
// This class could represent a simple human or artificial player.
public class Player {
// Your implementation goes here.
// Instance variables.
final static int OCEAN_SIZE = 10;
final static int FLEET_SIZE = 5;
public static Coordinate[][] ocean;
// Constructor.
protected Player(String name) {
// this.OCEAN_SIZE = 10;
// this.FLEET_SIZE;
this.ocean = new Coordinate[OCEAN_SIZE][OCEAN_SIZE];
// Method getOcean(): Accessor method.
public static Coordinate[][] getOcean() {
return ocean;
}
public static void printOcean() {//Coordinate.showShips) {
System.out.print(" ");
for (int i = 0; i < OCEAN_SIZE; i++) {
System.out.print(" " + i + " ");
}
for (int i = 0; i < OCEAN_SIZE; i++) {
System.out.println(" +");
for (int j = 0; j < OCEAN_SIZE; j++) {
System.out.print(" " + i + " ");
System.out.print("---+");
}
System.out.println(i + " ");
for (int j = 0; j < OCEAN_SIZE; j++) {
System.out.print(" " + i + " ");
Coordinate coordinate = ocean[i][j];
System.out.print(coordinate.printCoordinate(true));
}
}
}
}
=========== Coordinate Class =======================
package battleshipmodel;
// Class Coordinate contains all implementation for one coordinate of the ocean
// for any player. Can be references when dealing with a player's ocean or
// the opponent's "target" ocean.
public class Coordinate {
// Your implementation goes here.
// Instance variables.
final String HIT;
final String MISS;
final String EMPTY;
final String UNKNOWN;
public Ship ship;
public boolean isHit;
// Constructor.
protected Coordinate() {
this.HIT = "X";
this.MISS = "-";
this.EMPTY = " ";
this.UNKNOWN = " ";
this.ship = null;
this.isHit = false;
}
// Method setShip(): Mutator method.
public void setShip(Ship ship) {
this.ship = ship;
}
// Method hasShip(): Checks if ship at coordinates.
// Returns TRUE if ship at coordinate.
protected static boolean hasShip() {
// Coordinate ocean[][] = Player.getOcean();
// return ocean[][] == this.EMPTY;
return false;
}
}
I'm new to Java and I'm having trouble with this bit of code:
import java.util.Scanner;
public class BattleshipLogic {
private final int rows;
private final int cols;
private final boolean[][] hits;
private final boolean[][] ships;
public BattleshipLogic(int numRows, int numCols) {
this.rows = numRows;
this.cols = numCols;
this.hits = new boolean[rows][cols];
this.ships = new boolean[rows][cols];
}
public void startGame() {
placeShips();
boolean gameOver = false;
// draw field for the first time
drawUI();
while (!gameOver) {
Target target = askForTarget();
processTarget(target);
drawUI();
}
}
private Target askForTarget() {
Target t = new Target();
Scanner input = new Scanner(System.in);
System.out.print("Please enter your target:");
t = input.nextInt();
return t;
}
/*
* This is just an example. You have to draw the ships by yourself.
* If you don't like the way the UI is drawn, make your own stuff!
*/
private void drawUI() {
// draw the ui, see blatt01/oberfläche.txt for an example
System.out.println("Schiffeversenken");
System.out.println("================");
System.out.println();
// columns
System.out.print(" ");
for (int col = 0; col < this.cols; col++) {
System.out.print(col + " ");
}
System.out.println();
System.out.print(" _");
for (int col = 0; col < this.cols; col++) {
System.out.print("__");
}
System.out.println();
for (int row = 0; row < this.rows; row++) {
System.out.print(Character.toChars(3 + row));
System.out.print(" |");
System.out.println();
}
}
private void placeShips() {
// do useful stuff to place the ships here
// see Blatt01 for rules
}
private void processTarget(Target target) {
}
/**
* This class only holds the position
* of a target.
*/
private class Target {
public int row;
public int col;
}
}
Everytime I try to compile this error comes up:
error: incompatible types: int cannot be converted to BattleshipLogic.Target
I know that the types are different, but what kind of a type is Target? How can I get the user input to be assigned to t?
Thanks so much in advance!
I think you want to do this.
private Target askForTarget() {
Target t = new Target();
Scanner input = new Scanner(System.in);
System.out.print("Please enter your target:");
t.row = input.nextInt();
t.col = input.nextInt();
return t;
}
to assign the int value to
t of type Target
you need a
getter and setter method
on your t
e.g.
public class Target
{
private int myValue;
public void setMyValue(int myValue)
{
this.myValue=myValue;
}
public int getMyValue()
{
return myValue;
}
}
then in your askForTarget() method
t.setMyValue(input.nextInt());
return t;
if you ever want to use the int in t in other calling method you can use the t method
t.getMyValue();
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I have made a program inside of which, there is a specific method that makes sure that all of the objects in an array that point to null point to a blank space. For some reason, whenever I run the code, it gives me a java.lang.NullPointerException.
I understand what a NullPointerException is, which is why I added the if statement, so that it wouldn't give the error, but it still does
Code:
public class TextGraphics {
public static void main(String[] args) {
displaySize size = new displaySize(5,5);
displaySize.output(5,3,size,"H");
displaySize.run(size);
}
}
class displaySize {
public static int indent;
public static int sizeX = 0;
public static int sizeY = 0;
public displaySize() {
}
public displaySize(int screenX, int screenY) {
sizeX = screenX;
sizeY = screenY;
indent = sizeX;
}
public static void output(int x, int y, displaySize size, String print) {
rarray(size)[x + y * size.sizeX] = print;
}
public static String[] rarray(displaySize size) {
String [] display;
return display = new String[sizeX * sizeY];
}
public static void run(displaySize size) {
int next = 0;
for (int i = 0; i < sizeY; i++) {
for (int b = 0; b < indent; b++) {
next++;
if(rarray(size)[next].equals(null) )
{
System.out.print( rarray(size)[next] + " ");
rarray(size)[next] = " ";
}
System.out.print( rarray(size)[next] + " ");
}
System.out.println("/n");
}
}
}
first problem used .equals(null) instead of == null
second problem your code throws a arrayoutofindex because your next++ was in the wrong for loop
finally your new line character was wrong its \n not /n
corrected code
public class TextGraphics {
public static void main(String[] args) {
displaySize size = new displaySize(5,5);
displaySize.output(5,3,size,"H");
displaySize.run(size);
}
}
class displaySize {
public static int indent;
public static int sizeX = 0;
public static int sizeY = 0;
public displaySize() {
}
public displaySize(int screenX, int screenY) {
sizeX = screenX;
sizeY = screenY;
indent = sizeX;
}
public static void output(int x, int y, displaySize size, String print) {
rarray(size)[x + y * size.sizeX] = print;
}
public static String[] rarray(displaySize size) {
String [] display;
return display = new String[sizeX * sizeY];
}
public static void run(displaySize size) {
int next = 0;
for (int i = 0; i < sizeY; i++) {
next++;
for (int b = 0; b < indent; b++) {
if(rarray(size)[next]==(null) )
{
rarray(size)[next] = " ";
System.out.print( rarray(size)[next] + " ");
}
System.out.print( rarray(size)[next] + " ");
}
System.out.println("\n");
}
}
}
I have used an existing genetic algorithm from
here
and reworked it I but don't know what I'm doing wrong
This is the error that I get
Exception in thread "main" java.lang.NullPointerException at
simpleGa.Algorithm.crossover(Algorithm.java:69) at
simpleGa.Algorithm.evolvePopulation(Algorithm.java:34) at
simpleGa.GAprisonerdilemma.main(GAprisonerdilemma.java:41)
I can't figure out exactly where the mistake is. Read a lot about NullPointerException but couldn't figure it out
package simpleGa;
public class Population {
public static Individual[] individuals;
/*
* Constructors
*/
// Create a population
public Population(int populationSize, boolean initialise) {
individuals = new Individual[populationSize];
// Initialise population
if (initialise) {
// Loop and create individuals
for (int i = 0; i < size(); i++) {
Individual newIndividual = new Individual();
newIndividual.generateIndividual();
saveIndividual(i, newIndividual);
}
for(int i=0;i<size();i++)
{
if(i%2==1){Individual individual1=individuals[i-1];
Individual individual2=individuals[i];
if(individuals[i-1].getGene(i-1)==0 && individuals[i].getGene(i)==0){
individuals[i-1].fitness=individual1.fitness+1;
individuals[i].fitness=individual2.fitness+1;
}
if(individuals[i-1].getGene(i-1)==1 && individuals[i].getGene(i)==1){
individuals[i-1].fitness=individual1.fitness+2;
individuals[i].fitness=individual2.fitness+2;
}
if(individuals[i-1].getGene(i-1)==0 && individuals[i].getGene(i)==1){
individuals[i-1].fitness=individual1.fitness+3;
individuals[i].fitness=individual2.fitness+0;
}
if(individuals[i-1].getGene(i-1)==1 && individuals[i].getGene(i)==0){
individuals[i-1].fitness=individual1.fitness+0;
individuals[i].fitness=individual2.fitness+3;
}
}}}
}
/* Getters */
public Individual getIndividual(int index) {
return individuals[index];
}
public Individual getFittest() {
Individual fittest = individuals[0];
// Loop through individuals to find fittest
for (int i = 1; i < size(); i++) {
if (fittest.getFitness() <= getIndividual(i).getFitness()) {
fittest = getIndividual(i);
}
}
return fittest;
}
/* Public methods */
// Get population size
public int size() {
return individuals.length;
}
// Save individual
public void saveIndividual(int index, Individual indiv) {
individuals[index] = indiv;
}
}
package simpleGa;
public class Individual {
static int defaultGeneLength = 1000;
private long[] genes =new long [defaultGeneLength];
// Cache
public static int fitness = 0;
// Create a random individual
public void generateIndividual() {
for (int i = 0; i < size(); i++) {
long gene = Math.round(Math.random());
genes[i] = gene;
}
}
/* Getters and setters */
// Use this if you want to create individuals with different gene lengths
public static void setDefaultGeneLength(int length) {
defaultGeneLength = length;
}
public long getGene(int i) {
return genes[i];
}
public void setGene(int index, long value) {
genes[index] = value;
fitness = 0;
}
/* Public methods */
public int size() {
return genes.length;
}
public static int getFitness() {
return fitness;
}
public void setFitness(int i) {
fitness=i;
}
#Override
public String toString() {
String geneString = "";
for (int i = 0; i < size(); i++) {
geneString += getGene(i);
}
return geneString;
}
}
package simpleGa;
public class Algorithm {
/* GA parameters */
private static final double uniformRate = 0.5;
private static final double mutationRate = 0.015;
private static final int tournamentSize = 5;
private static final boolean elitism = true;
/* Public methods */
// Evolve a population
public static Population evolvePopulation(Population pop) {
Population newPopulation = new Population(pop.size(), false);
// Keep our best individual
if (elitism) {
newPopulation.saveIndividual(0, pop.getFittest());
}
// Crossover population
int elitismOffset;
if (elitism) {
elitismOffset = 1;
} else {
elitismOffset = 0;
}
// Loop over the population size and create new individuals with
// crossover
for (int i = elitismOffset; i < pop.size(); i++) {
Individual indiv1 = tournamentSelection(pop);
Individual indiv2 = tournamentSelection(pop);
Individual newIndiv = crossover(indiv1, indiv2);
newPopulation.saveIndividual(i, newIndiv);
}
// Mutate population
for (int i = elitismOffset; i < newPopulation.size(); i++) {
mutate(newPopulation.getIndividual(i));
}
for(int i=0;i<pop.size();i++)
{for(int j=0;j<pop.getIndividual(i).size();j++)
{if(i%2==1){Individual individual1=Population.individuals[i-1];
Individual individual2=Population.individuals[i];
if(Population.individuals[i-1].getGene(i-1)==0 && Population.individuals[i].getGene(i)==0){
Population.individuals[i-1].fitness=individual1.fitness+1;
Population.individuals[i].fitness=individual2.fitness+1;
}
if(Population.individuals[i-1].getGene(i-1)==1 && Population.individuals[i].getGene(i)==1){
Population.individuals[i-1].fitness=individual1.fitness+2;
Population.individuals[i].fitness=individual2.fitness+2;
}
if(Population.individuals[i-1].getGene(i-1)==0 && Population.individuals[i].getGene(i)==1){
Population.individuals[i-1].fitness=individual1.fitness+3;
Population.individuals[i].fitness=individual2.fitness+0;
}
if(Population.individuals[i-1].getGene(i-1)==1 && Population.individuals[i].getGene(i)==0){
Population.individuals[i-1].fitness=individual1.fitness+0;
Population.individuals[i].fitness=individual2.fitness+3;
} }}}``
return newPopulation;
}
// Crossover individuals
private static Individual crossover(Individual indiv1, Individual indiv2) {
Individual newSol = new Individual();
// Loop through genes
for (int i = 0; i < indiv1.size(); i++) {
// Crossover
if (Math.random() <= uniformRate) {
newSol.setGene(i, indiv1.getGene(i));
} else {
newSol.setGene(i, indiv2.getGene(i));
}
}
return newSol;
}
// Mutate an individual
private static void mutate(Individual indiv) {
// Loop through genes
for (int i = 0; i < indiv.size(); i++) {
if (Math.random() <= mutationRate) {
// Create random gene
long gene = Math.round(Math.random());
indiv.setGene(i, gene);
}
}
}
// Select individuals for crossover
private static Individual tournamentSelection(Population pop) {
// Create a tournament population
Population tournament = new Population(tournamentSize, false);
// For each place in the tournament get a random individual
for (int i = 0; i < tournamentSize; i++) {
int randomId = (int) (Math.random() * pop.size());
tournament.saveIndividual(i, pop.getIndividual(randomId));
}
// Get the fittest
Individual fittest = tournament.getFittest();
return fittest;
}
package simpleGa;
public class FitnessCalc {
/* Public methods */
// Set a candidate solution as a byte array
// To make it easier we can use this method to set our candidate solution
// with string of 0s and 1s
// Calculate inidividuals fittness by comparing it to our candidate solution
static int getFitness(Individual individual) {
int fitness = 0;
// Loop through our individuals genes and compare them to our cadidates
fitness=Individual.fitness;
return fitness;
}
}
// Get optimum fitness
}
package simpleGa;
import java.util.Scanner;
public class GAprisonerdilemma {
public static void main(String[] args) {
// Set a candidate solution
Scanner keyboard = new Scanner(System.in);
System.out.println("Input number of games!");
int k = keyboard.nextInt();
Individual.setDefaultGeneLength(k);
// Create an initial population
System.out.println("Input number of individuals in the population!");
int p = keyboard.nextInt();
Population myPop = new Population(p, true);
System.out.println("Input acceptable number of generations!");
int l = keyboard.nextInt();
// Evolve our population until we reach an optimum solution
int generationCount = 0;
int j=l+1;
System.out.println("Input requiered fitness value !");
int f = keyboard.nextInt();
int h=0;
// Evolve our population until we reach an optimum solution
for(int i=0;i<j;i++)
{
if(i==0){}
else{
if(myPop.getFittest().getFitness()>=f){if(h==0){h++;}
else{ System.out.println("Solution found!");
System.out.println("Generation: " + generationCount);
System.out.println( "Fitness(Points): " + myPop.getFittest().getFitness());
break;}
}else {myPop = Algorithm.evolvePopulation(myPop);
generationCount++;
System.out.println("Generation: " + generationCount + " Fittest: " + myPop.getFittest().getFitness());
}
if(i==j-1){ if(myPop.getFittest().getFitness()>=f)System.out.println("Solution found !");
else System.out.println("Solution not found closest solution is!");
System.out.println("Generation: " + generationCount);
System.out.println( " Fitness(Points): " + myPop.getFittest().getFitness());}
}
}
System.out.println("0 for betrays in that turn 1 for cooperates!");
System.out.println("Turns:");
System.out.println(myPop.getFittest());
}
}
OK so I have recently got my program to the point where it is allmost working, however I cant seem to figure out how to make my bug object move.
I have a class called AWorld that is populated with instances of a class method Randfood (ints between 0 and 9) in randomly placed possitions within the grid. It is also passed and instance of my class ABug as an attribute that is placed into the grip according to user input. my problem is I wish to make it move towards the food objects (my ints between 0-9) and when its next to them to have its energy level increased accordingly. it needs to only move towards an object when its within a set distance from it. i.e. 3 spaces in any direction, else just move randomly. my issue is i cant seem to figure out how to do that with my current code setup.
AWorld Class:
package finalversion2;
import java.util.Arrays;
import java.util.Random;
public class AWorld {
int x[] = new int[10], y[] = new int[10];
int row = 25;
int column = 25;
char[][] map;
public static int RandFood(int min, int max) {
Random rand = new Random(); // Initializes the random function.
int RandNum = rand.nextInt((max - min) + 1) + min; //generates a random number within the max and min ranges
return RandNum; //returns the random number
}
//Constructor
//Sets up map array for the AWorld object
//uses a bug that is passed to it
public AWorld(ABug bug) {
ABug bug1 = bug;
map = new char[row][column];
for (int i = 0; i < row; i++) {
for (int x1 = 0; x1 < column; x1++) {
map[i][x1] = ' ';
}
}
for (int i = 0; i < column; i++) {
Random rand = new Random();
int x = rand.nextInt(row);
int y = rand.nextInt(column);
map[x][y] = (char) RandFood(48, 57);
map[bug1.getHPossistion()][bug1.getVPossistion()] = bug1.getSymbol(); // gets the bugs x and y possistion in the array (user defined) and puts it into the symbol variable
}
}
public void PrintWorld() {
for (int i = 0; i < row; i++) //these next two for loops print the array to the screen
{
System.out.print("|");
for (int x1 = 0; x1 < column; x1++) {
System.out.print(map[i][x1]);
}
System.out.println("|");
}
}
}
ABug:
package finalversion2;
public class ABug
{
public static void main(){
}
private String species = new String(); //instance variables (defines data of object)
private String name = new String();
private String description = new String();
private char symbol;
private int hPossistion, vPossistion, energy, iD;
public ABug(){
}
public ABug (String s, String n, String d, int h, int v, int e, int i){
this.species = s;
this.name = n;
this.description = d;
this.symbol = s.charAt(0);
this.hPossistion = h;
this.vPossistion = v;
this.energy = e;
this.iD = i;
}
//setters
public void setSpecies(String s){
this.species = s;
}
public void setName(String n){
this.name = n;
}
public void setSymbol(char symbol){
this.symbol = symbol;
}
public void setHPossistion(int x){
this.hPossistion = x;
}
public void setVPossistion(int y){
this.vPossistion = y;
}
public void setEnergy(int energy){
this.energy = energy;
}
public void setID(int i){
this.iD = i;
}
public void setDescription(String d){
this.description = d;
}
//getters
public String getSpecies(){
return this.species;
}
public String getName(){
return this.name;
}
public char getSymbol(){
return this.symbol;
}
public int getHPossistion(){
return this.hPossistion;
}
public int getVPossistion(){
return this.vPossistion;
}
public int getEnergy(){
return this.energy;
}
public int getID(){
return this.iD;
}
public String getDescription(){
return this.description;
}
public String toString(){
String BugData;
BugData = name + " " + symbol + "\n" + species + "\n" + description;
return BugData;
}
}
enum Direction:
package finalversion2;
public enum Direction {
NORTH, EAST, SOUTH, WEST;
}
now im guessing I need to redraw my map each time i wish it to move using my enum based on a boolean response, i.e. call the printworld method but randomly move the bug. but wont that reprint my random ints?
please help. im very new to java.
Cheers in advance.