I have been searching for answers for this but no success. I have two arrays that I insert objects into and print the result on the screen. Now what am trying to do is to move each stored object in the array to a different coordinate and print the result. Any assistance will be appreciated.
public class Board {
int row = 0;
int col = 0;
public Ships ships=new Ships();
Controller controller = new Controller();
public Board(int rows,int columns)
{
board = new Ships[rows][columns];
this.r=rows;
this.c=columns;
}
public void addShip(int x,int y,Ships s)
{
board[x][y]=s;
}
public void print(ArrayList<Ships> player1)
{
for(int i = 0; i<row; i++)
{
for(int j = 0; j<col; j++)
{
ships=board[i][j];
if(ships==null)
{
System.out.print("-");
System.out.print("\t");
}
else
{
System.out.print(ships.getID());
System.out.print("\t");
}
}
System.out.println();
System.out.print("\n");
}
Scanner readinput = new Scanner(System.in);
String enterkey = "press enter key to continue....";
System.out.print(enterkey);
enterkey = readinput.nextLine();
System.out.print(enterkey);
if (enterkey.equals("")){
System.out.println("\n");
System.out.println("\n");
System.out.println("\n");
System.out.println("\n");
System.out.println("\n");
System.out.println("\n");
System.out.println("\n");
System.out.println("\n");
}
}
}
Your question is relatively unclear, but I am assuming that you want to move a ship at a specific position in your 2-d array (board) to another position.
A method like this should do what you want:
public void moveShip(int xFrom, int yFrom, int xTo, int yTo){
board[xTo][yTo] = board[xFrom][yFrom];
board[xFrom][yFrom] = null;
}
Related
I'm trying to make a battleship game, and this is the part where the players set their boards. When the second player to set the board makes theirs, the first player's board becomes the same as the second player's (when playing the game guessing the locations of that board are misses though, but that's another problem that will hopefully be fixed once this is). For example if I set the first player's ships as being at A1 A2 A3, B1 B2 B3, and C1 C2 C3, then set the second player's ships as D1 D2 D3, E1 E2 E3, and F1 F2 F3, when both lists of ships are printed out I get D1 D2 D3, E1 E2 E3, and F1 F2 F3 for both ships. I've found other questions on here with the same problem, but they always had the problem because they didn't make new lists every time, which I do (at least I'm pretty sure I do), so I can't find where my problem is. Here is the entire main game class, the GetShipLocations, SetShipLocations, and PlayersMakeTheirBoards, functions are what are giving me problems.
import java.util.*;
import java.lang.*;
public class MainGame {
InputReader read = new InputReader();
Grid p1Board = new Grid();
Grid p2Board = new Grid();
Grid p1ShipsBoard = new Grid();
Grid p2ShipsBoard = new Grid();
ArrayList<Ship> p1Ships = new ArrayList<Ship>();
ArrayList<Ship> p2Ships = new ArrayList<Ship>();
String activePlayer = "P1";
public void SetUp() {
p1Board.PrepPrintGrid();
p2Board.PrepPrintGrid();
Ship ship1 = new Ship();
Ship ship2 = new Ship();
Ship ship3 = new Ship();
p1Ships.add(ship1);
p1Ships.add(ship2);
p1Ships.add(ship3);
p2Ships.add(ship1);
p2Ships.add(ship2);
p2Ships.add(ship3);
}
public void GameIntro() {
System.out.println("Welcome to battleship!");
String rulesOption = read.getUserInput("Do you need to see the rules?");
if(rulesOption.equals("Yes") || rulesOption.equals("yes"))
{
System.out.println("Put rules here");
}
System.out.println("Randomly determining which player goes first");
int random = (int) (Math.random() * 2);
if(random == 1)
{
activePlayer = "P2";
}
System.out.println(activePlayer + " starts!");
}
public ArrayList<ArrayList<String>> GetShipLocations(Grid board) {
ArrayList<ArrayList<String>> ships = new ArrayList<ArrayList<String>>();
ArrayList<String> ship1 = new ArrayList<String>();
ArrayList<String> ship2 = new ArrayList<String>();
ArrayList<String> ship3 = new ArrayList<String>();
ships.add(ship1);
ships.add(ship2);
ships.add(ship3);
String[] numbers = {"first", "second", "third"};
board.PrepPrintGrid();
board.PrintGrid();
for(int i = 0; i < 3; i++)
{
for(int j = 0; j < 3; j++)
{
String coordinate = read.getUserInput("Enter the " + numbers[j] + " coordinate of your " + numbers[i] + " ship (3 long):");
ships.get(i).add(coordinate);
board.SetGridDisplay(coordinate, "hit");
board.PrintGrid();
}
}
return ships;
}
public void SetShipLocations(ArrayList<Ship> ship, Grid activeBoard) {
ArrayList<ArrayList<String>> shipLocations = GetShipLocations(activeBoard);
for(int i = 0; i < 3; i++) {
ship.get(i).SetCells(shipLocations.get(i));
}
}
public void PlayersMakeTheirBoards() {
if(activePlayer.equals("P1"))
{
System.out.println("Hand the computer to player one.");
System.out.println("Player one, time to set your board.");
SetShipLocations(p1Ships, p1ShipsBoard);//the effects of this seem to maybe be overriden when the second board is set
for(int i = 0; i < /*100*/3; i++)
{
for(int j = 0; j < 3; j++)
{
System.out.println(p1Ships.get(i).cells.get(j));
}
}
System.out.println("Hand the computer to player two.");
System.out.println("Player two, time to set your board.");
SetShipLocations(p2Ships, p2ShipsBoard);
for(int i = 0; i < /*100*/3; i++)
{
for(int j = 0; j < 3; j++)
{
System.out.println(p2Ships.get(i).cells.get(j));
}
}
for(int i = 0; i < /*100*/3; i++)
{
for(int j = 0; j < 3; j++)
{
System.out.println(p1Ships.get(i).cells.get(j));
}
}
}
else
{
System.out.println("Hand the computer to player two.");
System.out.println("Player two, time to set your board.");
SetShipLocations(p2Ships, p2ShipsBoard);
/*for(int i = 0; i < 100; i++)
{
System.out.println("");
}*/
for(int i = 0; i < /*100*/3; i++)
{
for(int j = 0; j < 3; j++)
{
System.out.println(p2Ships.get(i).cells.get(j));
}
}
System.out.println("Hand the computer to player one.");
System.out.println("Player one, time to set your board.");
SetShipLocations(p1Ships, p1ShipsBoard);
for(int i = 0; i < /*100*/3; i++)
{
for(int j = 0; j < 3; j++)
{
System.out.println(p1Ships.get(i).cells.get(j));
}
}
for(int i = 0; i < /*100*/3; i++)
{
for(int j = 0; j < 3; j++)
{
System.out.println(p2Ships.get(i).cells.get(j));
}
}
}
}
public void PlayTheGame() {
String guess = new String();
String result = new String();
for(int i = 0; i < 100; i++)
{
System.out.println("");
}
while(!p1Ships.isEmpty() && !p2Ships.isEmpty())
{
if(activePlayer.equals("P1"))
{
//print the grid
p1Board.PrintGrid();
//ask user for their guess
guess = read.getUserInput("Player one, enter your guess:");
for(Ship boat:p2Ships)
{
result = boat.CheckYourself(guess);
if(result.equals("hit"))
{
System.out.println(result + "!");
break;
}
if(result.equals("kill"))
{
System.out.println(result + "!");
p2Ships.remove(boat);
break;
}
}
if(result.equals("miss"))
{
System.out.println(result);
}
p1Board.SetGridDisplay(guess, result);
activePlayer = "P2";
}
else
{
p2Board.PrintGrid();
//ask user for their guess
guess = read.getUserInput("Player two, enter your guess:");
for(Ship boat:p1Ships)
{
result = boat.CheckYourself(guess);
if(result.equals("hit"))
{
System.out.println(result + "!");
break;
}
if(result.equals("kill"))
{
System.out.println(result + "!");
p1Ships.remove(boat);
break;
}
}
if(result.equals("miss"))
{
System.out.println(result);
}
p2Board.SetGridDisplay(guess, result);
activePlayer = "P1";
}
}
}
public void EndTheGame() {
String winner = new String();
if(p1Ships.isEmpty())
{
winner = "Player two";
p2Board.PrintGrid();
}
else
{
winner = "Player one";
p1Board.PrintGrid();
}
System.out.println("The game is over!");
System.out.println(winner + " wins! Congratulations!");
}
public static void main(String[] args) {
MainGame game = new MainGame();
game.SetUp();
game.GameIntro();
game.PlayersMakeTheirBoards();
game.PlayTheGame();
game.EndTheGame();
}
}
and here is the Ship class
import java.util.*;
public class Ship {
ArrayList<String> cells = new ArrayList<String>();
//String name = new String();
public void SetCells(ArrayList<String> locations) {
cells = locations;
}
/*public void SetName(String word) {
name = word;
}*/
public String CheckYourself(String guess) {
if(cells.contains(guess))
{
cells.remove(guess);
if(cells.isEmpty())
{
return "kill";
}
else
{
return "hit";
}
}
return "miss";
}
}
The grid and reader classes are working perfectly so I didn't include them.
(This is all based off the dotcom battleship game in headfirst java)
In your setup function:
public void SetUp() {
p1Board.PrepPrintGrid();
p2Board.PrepPrintGrid();
Ship ship1 = new Ship();
Ship ship2 = new Ship();
Ship ship3 = new Ship();
p1Ships.add(ship1);
p1Ships.add(ship2);
p1Ships.add(ship3);
p2Ships.add(ship1);
p2Ships.add(ship2);
p2Ships.add(ship3);
}
You are adding the same instances of ship1-3 to both p1Ships and p2Ships. So when you change the ships of player 2, the p1Ships ArrayList is still pointing to the same ships as p2Ships, and thus will always be the same.
This getsize method asks for numbers to blank in a square matrix. After input it returns the new matrix. I would like to check these values in a do-while loop. I added the full code. I would like to print out if one of the entered values occurs more than once and then give the option to change that spot in the matrix to a new number.
import java.util.Scanner;
public class square {
private int [][]matrixblank;
private int firstrow;
private int number;
private int count;
public square() {
matrixblank=getsize();
firstrow=0;
number=0;
count=0;
}
public int [][]getsize() {
int rows=0;
int f=0;
Scanner size = new Scanner(System.in);
//THIS SETS SIZE OF THE MATRIX
System.out.println("How big do you want your magic square?");
rows=size.nextInt();
while(rows<1){
System.out.println("Enter an accepted value of the size of your magic square");
rows=size.nextInt();}
// END OF SETTING MATRIX
// FINDS VALUE OF THE NUMBERS IN THE MATRIX
int matrix[][]= new int [rows][rows];
for(int row=0; row<matrix.length;row++){
for(int column=0;column<matrix[row].length;column++){
System.out.println("Enter value for"+ row + " "+ column);
f=size.nextInt();
matrix[row][column]=f;
//END OF FINDING VALUES
//CHECKS TO SEE IF THE VALUE IS TOO BRING OR SMALL
while(f<1||f>matrix.length*matrix.length){
System.out.println("This number is too big or small please. Enter a new Number.");
f=size.nextInt();
matrix[row][column]=f;
}
//END OF CHECKING IF THE VALUE IS IN BOUNDS
if(matrix[row][column]==f){
System.out.println("Enter a new number that hasnt been entered before");
f=size.nextInt();
matrix[row][column]=f;
}
}}
return matrix;
}
public void sumoffirstrow() {
for(int firstrow1=0;firstrow1<matrixblank[0].length;firstrow1++) {
firstrow+=matrixblank[0][firstrow1];
number=firstrow;
}
}
public boolean checkrows(){
int sumrows=0;
for(int a=0;a<matrixblank.length;a++){
sumrows=0;
for(int b=0;b<matrixblank.length;b++){
sumrows+=matrixblank[a][b];
}
if(sumrows!=number){
return false;
}
}
return true;
}
public boolean checkcolumns(){
int sumcolumns=0;
for(int c =0; c < matrixblank.length; c++){
sumcolumns = 0;
for(int d = 0; d< matrixblank.length; d++){
sumcolumns += matrixblank[d][c];
}
if(sumcolumns != number){
return false;
}
}
return true;
}
public boolean TLBR(){
int sumofLtoR;
sumofLtoR=0;
for(int e=0;e<matrixblank.length;e++){
sumofLtoR+=matrixblank[e][e];
}
if(sumofLtoR!=number){
return false;
}
return true;
}
public boolean TRBL(){
int sumofRtoL;
sumofRtoL=0;
for(int f=0;f<matrixblank.length;f++){
sumofRtoL+=matrixblank[f][matrixblank.length-1-f];
}
if(sumofRtoL!=number){
return false;
}
return true;
}
public String getnumbers() {
String b = "";
for(int i = 0; i < matrixblank.length; i++){
b +="\n";
for(int j = 0; j < matrixblank[0].length; j++){
b += " " + matrixblank[i][j];
}
}
return b;
}
public String toString() {
if(checkrows()&&checkcolumns()&&TLBR()&&TRBL()){
return "This is a magic square"+getnumbers();
}
else{
return "This is not a magic square\n"+getnumbers();
}
}
}
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();
I'm working on an assignment that takes a data file with a number matrix and determines if it is a magic square. If it is then it also needs to report the sum of the rows and columns. With the output:
The matrix is a magic square.
The sum of all the rows and columns is 34.
I'm not sure how to go about this with one method, I feel like its asking me to return 2 values. The closest I have came is by adding a System.out.println with the sum at the end of my method when it returns true.
But the issue with that is that my output is backwords:
The sum of all the rows and columns is 34.
The matrix is a magic square.
How do I get the sum when I've only been asked to create one method? Below is my code, the instructor gave the bottom 3 methods so I'm only concerned with the first 2.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class chp8magic
{
public static void main(String args[])
{
int matrix[][] = initMatrix();
printData(matrix);
if (isMagic(matrix)) {
System.out.println("The matrix is a magic square.");
}
else {
System.out.println("Not a magic square");
}
}
public static boolean isMagic(int[][] mat)
{
int n = mat.length;
int nSquare = n*n;
int M = (n*n*(n*n+1)/2)/n;
int sumRow = 0, sumColoumns = 0, sumPriDiag = 0, sumSecDiag = 0;
boolean[] flag = new boolean[n*n];
for(int row = 0; row < n; row++){
sumRow = 0;
sumColoumns = 0;
for(int col = 0; col < n; col++)
{
if( mat[row][col] < 1 || mat[row][col] > nSquare )
return false;
if(flag[mat[row][col]-1] == true)
return false;
flag[mat[row][col]-1] = true;
sumRow += mat[row][col];
sumColoumns += mat[col][row];
}
sumPriDiag += mat[row][row];
sumSecDiag += mat[row][n-row-1];
if(sumRow!=M || sumColoumns!=M)
return false;
}
if(sumPriDiag!=M || sumSecDiag!=M)
return false;
else
return true;
}
public static int[][] initMatrix()
{
int matrix[][];
Scanner filein = null;
try {
filein = new Scanner(new File("matrix.txt"));
int numRows = Integer.parseInt(filein.nextLine());
matrix = new int[numRows][];
parseData(matrix, filein);
filein.close();
return matrix;
} catch (FileNotFoundException e) {
System.out.println(e.getMessage());
if(filein != null)
filein.close();
return null;
}
}
public static void parseData(int matrix[][], Scanner in)
{
for(int r = 0; r < matrix.length; r++)
{
String splitLine[] = in.nextLine().split(" ");
matrix[r] = new int[splitLine.length];
for(int c = 0; c < matrix[r].length; c++){
matrix[r][c] = Integer.parseInt(splitLine[c]);
}
}
}
public static void printData(int matrix[][])
{
for(int r = 0; r < matrix.length; r++){
for(int c = 0; c < matrix[r].length; c++){
System.out.print(matrix[r][c] + " ");
}
System.out.println();
}
}
}
Probably you just need to do:
System.out.println("is magic: " + isMagic);
System.out.ptintln("sum: " + sum);
However this is not really returning the values, just printing them. To return two values there are several options. You could return an object:
public class MagicSquareProperties {
private boolean magic;
private int sum;
public MagicSquareProperties(boolean magic, int sum) {
this.magic = magic;
this.sum = sum;
}
public boolean isMagic() {
return magic;
}
public int getSum() {
return sum;
}
}
// now to return both values: return new MagicSquareProperties(true, 34);
But in my opinion the best solution would be the following:
Create a class MagicSquare.
Add property declarations (e.g. private int sum).
Add a constructor, for example MagicSquare(File file), this constructor reads the file and populates the properties.
Add getters and setters if needed (e.g. getSum())
Execute the main method in another class and call new MagicSquare(...) to create a magic square object. Afterwards you can call the getters on the object whenever you need the value.
So far I wrote code that makes a table looking kind of like the table from excel and I am able to input letters words when it compiles, but I cant say for example 1a equals 5 and make the cell in 1a show 5 inside it.this is what my table looks like so far. This is my code to draw up the table:
package table;
public class Spreadsheat {
private int xVal = 137;
private int yVal = 1;
private int[][] table = new int [20][20];
private char yaxis = 'A';
private int xaxis = 0;
public Spreadsheat(){
for(int i = 0; i < xVal; i++){
System.out.print("-");
}
System.out.println();
System.out.print(" |");
for(int i = 0; i < 17; i++){
System.out.print("| " + yaxis + "\t" + "|" );
yaxis = (char) (yaxis + 1);
}
System.out.println();
for(int i = 0; i < xVal; i++){
System.out.print("-");
}
System.out.println();
for(int j = 0; j <10;j++){
System.out.print(" " + xaxis + "|");
for(int i = 0; i < 17; i++){
System.out.print("|" + "\t" + "|" );
}
System.out.println();
xaxis = xaxis + 1;
}
}
public void setxval(int xVal) {
this.xVal = xVal;
}
public int getxVal() {
return xVal;
}
public void setyVal(int yVal) {
this.yVal = yVal;
}
public int getyVal() {
return yVal;
}
public void setTable(int table[][]) {
this.table = table;
}
public int[][] gettable() {
return table;
}
}
And this is my client program:
package Client;
import java.util.Scanner;
import table.Spreadsheat;
public class VisiCalc {
public static void main(String[] args){
Scanner kb = new Scanner(System.in);
Spreadsheat table = new Spreadsheat();
boolean end = false;
while(end == false){
String input = kb.next();
System.out.println(input);
if(input.contains("quit")){
end = true;
}
}
}
}
Your Spreadsheet needs a way to update table. For example, you need a method like this in your Spreadsheet class:
public void setValue(int row, int col, int value) {
if (row >= 0 && row < 20 && col >=0 && col < 20) {
table[row][col] = value;
}
}
You need a method way to convert your keyboard input so you can call table.setValue(...). For example, if you enter "2A=8", your method should parse that string into x=1, y=0, v=8 and call table.setValue(x,y,v). It's up to you if you want the method in Spreadsheet or in your client.
You need a method in Spreadsheet so you can print out your table to the screen with the updated content. You will realize you need to format your content so that your columns line up properly. The easiest way is to set each column to a fixed width say 8 and use java.text.DecimalFormat to convert your int to String.
I guess this is a start.