How to input numbers into a cell of a table? - java

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.

Related

Beginner: How to return user input?

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();

How do I debug a NullPointerException? [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
I am trying to place ships on a console based board game, I have the following errors and not sure how to debug them.
Exception in thread "main" java.lang.NullPointerException
at NavalBattle.Board.print(Board.java:570)
at NavalBattle.Board.placeShipsP1(Board.java:267)
at NavalBattle.Board.(Board.java:61)
at NavalBattle.Controller.start(Controller.java:29)
at NavalBattle.Controller.main(Controller.java:21)
line 570 is value = this.ships2[row][col].toString();
import java.util.Scanner;
public class Controller {
/**
* The board that represents the current state of the game.
*/
private Board board;
public Controller() {}
/**
* This creates one Library object and calls its start method.
*
* #Param args
*/
public static void main(String[] args) {
new Controller().start();
}
int PL;
/**
* The PLrimary method that starts and coordinates a game. Call this to
* begin a new game.
*/
public void start() {
this.board = new Board();
Scanner scanner = new Scanner(System.in);
this.board.moveShip();
while (!this.board.isGameOver()) {
PL = 1;
this.board.moveShip();
PL = 2;
this.board.moveShip2(null);
this.board.remap();
this.board.moveShip2(null);
System.out.println("Enter a row and column number at which to shoot (e.g., 2,3): ");
String[] coordinates = scanner.nextLine().split(",");
if (coordinates.length != 2) {
System.out.println("PLlease enter coordinates in the correct format.");
continue;
}
int row = Integer.parseInt(coordinates[0].trim());
int column = Integer.parseInt(coordinates[1].trim());
this.board.bombOp(row, column);
}
if (PL == 1);{
System.out.println("Game Over Player 2 wins");
}
if (PL == 2){
System.out.println("Game Over Player 1 wins");
}
}
}
// Board Class
import java.util.ArrayList;
import java.util.Scanner;
public class Board {
int x = 0;
int y = 0;
ArrayList<Ships> player1 = new ArrayList<>();
ArrayList<Ships> player2 = new ArrayList<>();
/**
* The number of shots that have hit ships
*/
private int hitCount;
/**
* Track the locations of the board that have been fired upon
*/
private boolean[][] locationsFiredUpon;
/**
* Track the ships in the game
*/
private Ships[][] ships;
private Ships[][] ships2;
private Ships[][] shipsM;
/**
* The number of ships sunk
*/
private int shipsSunk;
/**
* The number of shots fired
*/
private int shotsFired;
/**
* Constructor. Initializes internal counters and populates the game
* board with randomly placed ships.
*/
public Board() {
this.hitCount = 0;
this.shipsSunk = 0;
this.shotsFired = 0;
board();
this.ships = new Ships[6][9];
this.ships2 = new Ships[6][9];
this.locationsFiredUpon = new boolean[6][9];
for (int row=0; row < this.ships.length; row++) {
for (int col=0; col < this.ships[row].length; col++) {
this.ships[row][col] = new Conflict();
this.locationsFiredUpon[row][col] = false;
}
}
this.placeShipsP1();
this.placeShipsP2();
this.moveShip();
this.moveShip2(player1);
}
public void remap() {
board();
this.locationsFiredUpon = new boolean[6][9];
for (int row=0; row < this.ships.length; row++) {
for (int col=0; col < this.ships[row].length; col++) {
this.ships[row][col] = new Conflict();
this.locationsFiredUpon[row][col] = false;
}
}
}
/**
* Constructor for testing. Accepts an input ship array and does not
* attempt to place ships
* #param shipArray
*/
public Board(Ships[][] shipArray) {
this.hitCount = 0;
this.shipsSunk = 0;
this.shotsFired = 0;
this.ships = shipArray;
this.locationsFiredUpon = new boolean[6][9];
for (int row=0; row < this.ships.length; row++) {
for (int col=0; col < this.ships[row].length; col++) {
this.locationsFiredUpon[row][col] = false;
}
}
}
public void board(){
this.ships = new Ships[6][9];
this.ships2 = new Ships[6][9];
}
/**
* Get the number of shots fired that have hit a ship.
* #return The number of shots fired that have hit a ship
*/
public int getHitCount() {
return this.hitCount;
}
/**
* Get the game board.
* #return A 2-D array of Ships representing the game
*/
public Ships[][] getShipArray() {
return this.ships;
}
public Ships[][] getShipArray2() {
return this.ships2;
}
/**
* Get the number of ships sunk.
* #return The number of ships sunk
*/
public int getShipsSunk() {
return this.shipsSunk;
}
/**
* Get the number of shots fired so far.
* #return The number of shots fired
*/
public int getShotsFired() {
return this.shotsFired;
}
/**
* Create an list of ships that can be placed on the board:
* - 1 battleship
* - 2 cruisers
* - 3 destroyers
* - 4 submarines
* #return ships to be placed on the board
*/
private ArrayList<Ships> generateInitialShipArrayList1() {
ArrayList<Ships> ship = new ArrayList<Ships>();
for (int i=0; i<1; i++) {
ship.add(new Battleship());
}
for (int i=0; i<0; i++) {
ship.add(new Minesweeper());
}
for (int i=0; i<0; i++) {
ship.add(new Destroyer());
}
for (int i=0; i<0; i++) {
ship.add(new Submarine());
}
for (int i=0; i<0; i++) {
ship.add(new Mines());
}
return ship;
}
private ArrayList<Ships> generateInitialShipArrayList2() {
ArrayList<Ships> ship2 = new ArrayList<Ships>();
for (int i=1; i<2; i++) {
ship2.add(new Battleship());
}
for (int i=1; i<1; i++) {
ship2.add(new Minesweeper());
}
for (int i=1; i<1; i++) {
ship2.add(new Destroyer());
}
for (int i=1; i<1; i++) {
ship2.add(new Submarine());
}
for (int i=1; i<1; i++) {
ship2.add(new Mines());
}
return ship2;
}
/**
* Indicate whether the game is over by checking if all ships have been
* sunk.
* #return true if all ships are sunk; otherwise false
*/
public boolean isGameOver() {
return (this.shipsSunk == 1);
}
/**
* Whether the specified position is occupied by a ship and is not empty
* sea.
* #param row
* #param column
* #return true if the position has a ship; else false
*/
public boolean isOccupied(int row, int column) {
System.out.println("Occupardo, you no go here");
return !(this.ships[row][column] instanceof Conflict);
}
public void placeShipsP1() {
System.out.println("");
print();
ArrayList<Ships> shipsToMove = this.generateInitialShipArrayList1();
player1 = this.generateInitialShipArrayList1();
boolean okToPlaceShipHere = false;
int row = 0;
int column = 0;
String Tp = "1";
boolean horizontal = false;
if(okToPlaceShipHere = false){
System.out.println("Occupardo, you no go here");
}
for (Ships ship : player1) {
while (!okToPlaceShipHere) {
Scanner scanner = new Scanner( System.in );
System.out.println("player1 enter a row and column (e.g., 2,3)");
System.out.println("please enter the row of " + ship.getShipType());
String[] coordinates = scanner.nextLine().split(",");
if (coordinates.length != 2) {
System.out.println("Please enter coordinates in the correct format.");
continue;
}
row = Integer.parseInt(coordinates[0].trim());
column = Integer.parseInt(coordinates[1].trim());
ship.setX(row);
ship.setY(column);
System.out.println(ship.getX() + " " + ship.getY());
// row = Random.nextInt(6);
// column = Random.nextInt(9);
horizontal = true;
okToPlaceShipHere = ship.okToPlaceShipAt(row, column, horizontal, this);
}
if( okToPlaceShipHere = true){
this.bombOp(row, column);
}
ship.setBowColumn(column);
ship.setBowRow(row);
ship.setPlayer(Tp);
ship.setX(row);
ship.setY(column);
System.out.println(ship.getX() + " " + ship.getY() + " " + ship.getPlayer());
ship.setHorizontal(horizontal);
this.placeShipIntoShipsArray(ship);
okToPlaceShipHere = false;
System.out.println("");
print();
}
}
public void placeShipsP2() {
System.out.println("");
print();
ArrayList<Ships> shipsToPlace = this.generateInitialShipArrayList1();
player2 = this.generateInitialShipArrayList2();
boolean okToPlaceShipHere = false;
int row = 0;
int column = 0;
String Tp = "2";
boolean horizontal = false;
if(okToPlaceShipHere = false){
System.out.println("Occupardo, you no go here");
}
for (Ships ship : player2) {
while (!okToPlaceShipHere) {
Scanner scanner = new Scanner( System.in );
System.out.println("Player 2 enter a row and column (e.g., 2,3)");
System.out.println("please enter the row of " + ship.getShipType());
String[] coordinates = scanner.nextLine().split(",");
if (coordinates.length != 2) {
System.out.println("Please enter coordinates in the correct format.");
continue;
}
row = Integer.parseInt(coordinates[0].trim());
column = Integer.parseInt(coordinates[1].trim());
ship.setX(row);
ship.setY(column);
System.out.println(ship.getX() + " " + ship.getY());
// row = random.nextInt(6);
// column = random.nextInt(9);
horizontal = true;
okToPlaceShipHere = ship.okToPlaceShipAt(row, column, horizontal, this);
}
ship.setBowColumn(column);
ship.setBowRow(row);
ship.setPlayer(Tp);
ship.setX(row);
ship.setY(column);
System.out.println(ship.getX() + " " + ship.getY() + " " + ship.getPlayer());
ship.setHorizontal(horizontal);
this.placeShipIntoShipsArray(ship);
okToPlaceShipHere = false;
System.out.println("");
print();
}
}
/**
* Place the given ship into locations in the
* 2Darray that tracks ship positions.
* #param ship
*/
private void placeShipIntoShipsArray(Ships ship) {
int row = ship.getBowRow();
int column = ship.getBowColumn();
// player1.add.ship;
player1.removeAll(player1);
player2.removeAll(player2);
if (ship.isHorizontal()) {
for (int i=0; i < ship.getLength(); i++) {
this.ships[row][(column+i)] = ship;
}
}
else {
for (int i=0; i < ship.getLength(); i++) {
this.ships[(row+i)][column] = ship;
}
}
}
public void ifship(){
for (int i=0; i < 1; i++){
board();
}
}
private void placeShipIntoShipsArray2(Ships ship) {
int row = ship.getBowRow();
int column = ship.getBowColumn();
//player1.add.ships;
player1.removeAll(player1);
player2.removeAll(player2);
//ship.clear();
if (ship.isHorizontal()) {
for (int i=0; i < ship.getLength(); i++) {
this.ships2[row][(column+i)] = ship;
}
}
else {
for (int i=0; i < ship.getLength(); i++) {
this.ships2[(row+i)][column] = ship;
}
}
}
public void display() {
System.out.print(" ");
for (int i=0; i < 9; i++) {
System.out.print(i + " ");
}
System.out.print("\n");
for (int row=0; row < 6; row++) {
System.out.print(" " + row + " ");
for (int col=0; col < 9; col++) {
String value = "";
if (this.locationsFiredUpon[row][col]) {
value = "-";
}
if (this.ships2[row][col] != null) {
value = this.ships2[row][col].toString() ;
}
else {
value = "-";
}
System.out.print(value + " ");
}
System.out.print("\n");
}
remap();
}
boolean pr = false;
boolean pr2 = false;
public void moveShip(){
System.out.println("So you wanna move a ship");
System.out.println(player1);
for (int i=0; i > 1; i++) {
print();
System.out.println("map 1");
pr = true;
}
if (pr = true){
display();
}
//ArrayList<Ships> shipsToMove = new ArrayList<>();
ArrayList<Ships> shipsToMove = new ArrayList<>();
ArrayList<Ships> shipsToMove1 = player1;
boolean notMoved = false;
int rowM = 0;
int columnM = 0;
String Tp = "1";
boolean horizontal = false;
if(notMoved = false){
System.out.println("Occupardo, you no go here");
}
System.out.println("gets here 1");
for (Ships shipM : shipsToMove1) {
System.out.println("gets here 2");
while (!notMoved) {
Scanner scanner1 = new Scanner( System.in );
System.out.println("Enter a area to move to (e.g., 2,3)");
System.out.println("please enter a movement for the: " + shipM.getShipType() + shipM.getBowRow());
String[] coordinates = scanner1.nextLine().split(",");
if (coordinates.length != 2) {
System.out.println("Please enter coordinates in the correct format.");
continue;
}
rowM = Integer.parseInt(coordinates[0].trim());
columnM = Integer.parseInt(coordinates[1].trim());
// row = random.nextInt(6);
// column = random.nextInt(9);
horizontal = true;
notMoved = shipM.okToPlaceShipAt(rowM, columnM, horizontal, this);
}
if( notMoved = true){
this.bombOp(rowM, columnM);
}
shipM.setBowColumn(columnM);
shipM.setBowRow(rowM);
shipM.setHorizontal(horizontal);
this.placeShipIntoShipsArray2(shipM);
notMoved = false;
System.out.println("");
display();
}
}
public void moveShip2(ArrayList<Ships> player2){
System.out.println("So you wanna move a ship");
for (int i=0; i > 1; i++) {
display();
pr2 = true;
}
if (pr2 = true){
display();
}
ArrayList<Ships> shipsToMove = new ArrayList<>();
player2 = this.player2;
boolean notMoved = false;
int rowM = 0;
int columnM = 0;
String Tp = "1";
boolean horizontal = false;
if(notMoved = false){
System.out.println("Occupardo, you no go here");
}
System.out.println("gets here 1");
for (Ships ship : player2) {
System.out.println("gets here 2");
while (!notMoved) {
Scanner scanner1 = new Scanner( System.in );
System.out.println("Enter a area to move to (e.g., 2,3)");
System.out.println("please enter a movement for the: " + ship.getShipType());
String[] coordinates = scanner1.nextLine().split(",");
if (coordinates.length != 2) {
System.out.println("Please enter coordinates in the correct format.");
continue;
}
rowM = Integer.parseInt(coordinates[0].trim());
columnM = Integer.parseInt(coordinates[1].trim());
// row = random.nextInt(6);
// column = random.nextInt(9);
horizontal = true;
notMoved = ship.okToPlaceShipAt(rowM, columnM, horizontal, this);
}
if( notMoved = true){
this.bombOp(rowM, columnM);
}
ship.setBowColumn(columnM);
ship.setBowRow(rowM);
ship.setHorizontal(horizontal);
this.placeShipIntoShipsArray2(ship);
notMoved = false;
System.out.println("");
display();
display();
}
}
/**
* Print the current state of the game.
*/
public void print() {
System.out.print(" ");
for (int i=0; i < 9; i++) {
System.out.print(i + " ");
}
System.out.print("\n");
for (int row=0; row < 6; row++) {
System.out.print(" " + row + " ");
for (int col=0; col < 9; col++) {
String value = "";
if (this.locationsFiredUpon[row][col]) {
value = "-";
}
**if (this.ships[row][col] != null) {
value = this.ships[row][col].toString() ;**
}
if (this.locationsFiredUpon[row][col]) {
value = this.ships2[row][col].toString();
}
if (this.ships2[row][col] != null) {
value = this.ships2[row][col].toString() ;
}
else {
value = "-";
}
System.out.print(value + " ");
}
System.out.print("\n");
}
}
public void print2() {
System.out.print(" ");
for (int i=0; i < 9; i++) {
System.out.print(i + " ");
}
System.out.print("\n");
for (int row=0; row < 6; row++) {
System.out.print(" " + row + " ");
for (int col=0; col < 9; col++) {
String value = "";
if (this.locationsFiredUpon[row][col]) {
value = "-";
}
if (this.shipsM[row][col] != null) {
value = this.shipsM[row][col].toString() ;
}
if (this.locationsFiredUpon[row][col]) {
value = this.ships2[row][col].toString();
}
if (this.ships2[row][col] != null) {
value = this.ships2[row][col].toString() ;
}
else {
value = "-";
}
System.out.print(value + " ");
}
System.out.print("\n");
}
board();
}
/**
* Handle a shot fired at the specified position.
* #param row
* #param column
* #return true if a ship was hit; else false
*/
public boolean bombOp(int row, int column) {
this.shotsFired++;
this.locationsFiredUpon[row][column] = true;
Ships shipAtLocation = this.ships[row][column];
if (shipAtLocation.isSunk()) {
return false;
}
boolean shipWasHit = shipAtLocation.bombOp(row, column);
if (shipWasHit) {
this.hitCount++;
}
if (shipAtLocation instanceof Conflict) {
return shipWasHit;
}
if (shipAtLocation.isSunk()) {
shipsSunk++;
}
return shipWasHit;
}
The best way to debug NullPointerException is to look at the first line of the stack trace, which is:
NavalBattle.Board.print(Board.java:570)
What this means is that the error occurred on line number 570 in the Board.java file. You should go to this line in the file and look at which variables could be null on that line.
Line 570 is value = this.ships2[row][col].toString();. On this line, only 3 things can possibly be null:
this.ships2
`this.ships2[row]
`this.ships2[row][col]
If you cannot immediately see which of these is null, use your IDE to set a breakpoint there and start your program in debug mode. When the IDE stops at that line, create a "watch expression" for each of the above 3 expressions, or use the "evaluate expression" feature. One of them should be null.
Without debugging, I can only guess, but I think I can make a good guess. this.ship2 is unlikely to be null because I can see that you have initialised it in your code. I also don't think that this.ships2[row] is null - You have initialised the 2D array in the constructor correctly I think. Therefore, I think it is this.ships2[row][col] that is null, and calling toString() on null is throwing the NPE. To confirm my theory you could replace the line with:
value = String.valueOf(this.ships2[row][col]);

Magic Square Method needs to output if it is a magic square and the sum of rows and columns

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.

How to fill a multidimensional array dependant on variables

The program I am working on is a simple shipping program. What I am having difficulty with is populating a multidimensional array factoring in certain variables.
Example
320 items need to be shipped out to 1 receiver using different box sizes.
XL can hold 50 items
LG can hold 20 items
MD can hold 5 items
SM can hold 1 items
Use the least number of boxes so far.
Code
This is my code so far.
import java.util.Scanner;
public class Shipping {
public static void main(String [] args) {
Scanner kbd = new Scanner(System.in);
final int EXTRA_LARGE = 50;
final int LARGE = 20;
final int MEDIUM = 5;
final int SMALL = 1;
String sBusinessName = "";
int iNumberOfGPS = 0;
int iShipmentCount = 0;
displayHeading(kbd);
iShipmentCount = enterShipments(kbd);
int[][] ai_NumberOfShipments = new int [iShipmentCount][4];
String[] as_BusinessNames = new String [iShipmentCount];
for (int iStepper = 0; iStepper < iShipmentCount; iStepper++) {
sBusinessName = varifyBusinessName(kbd);
as_BusinessNames[iStepper] = sBusinessName;
iNumberOfGPS = varifyGPS(kbd);
calculateBoxes(ai_NumberOfShipments[iStepper],iNumberOfGPS, EXTRA_LARGE, LARGE, MEDIUM, SMALL);
}
//showArray(as_BusinessNames);
}
public static void displayHeading(Scanner kbd) {
System.out.println("Red River Electronics");
System.out.println("Shipping System");
System.out.println("---------------");
return;
}
public static int enterShipments(Scanner kbd) {
int iShipmentCount = 0;
boolean bError = false;
do {
bError = false;
System.out.print("How many shipments to enter? ");
iShipmentCount = Integer.parseInt(kbd.nextLine());
if (iShipmentCount < 1) {
System.out.println("\n**Error** - Invalid number of shipments\n");
bError = true;
}
} while (bError == true);
return iShipmentCount;
}
public static String varifyBusinessName(Scanner kbd) {
String sBusinessName = "", sValidName = "";
do {
System.out.print("Business Name: ");
sBusinessName = kbd.nextLine();
if (sBusinessName.length() == 0) {
System.out.println("");
System.out.println("**Error** - Name is required\n");
} else if (sBusinessName.length() >= 1) {
sValidName = sBusinessName;
}
} while (sValidName == "");
return sValidName;
}
public static int varifyGPS(Scanner kbd) {
int iCheckGPS = 0;
int iValidGPS = 0;
do {
System.out.print("Enter the number of GPS receivers to ship: ");
iCheckGPS = Integer.parseInt(kbd.nextLine());
if (iCheckGPS < 1) {
System.out.println("\n**Error** - Invalid number of shipments\n");
} else if (iCheckGPS >= 1) {
iValidGPS = iCheckGPS;
}
} while(iCheckGPS < 1);
return iValidGPS;
}
public static void calculateBoxes(int[] ai_ToFill, int iNumberOfGPS) {
for (int iStepper = 0; iStepper < ai_ToFill.length; iStepper++)
}
//public static void showArray( String[] ai_ToShow) {
// for (int iStepper = 0; iStepper < ai_ToShow.length; iStepper++) {
// System.out.println("Integer at position " + iStepper + " is " + ai_ToShow[iStepper]);
// }
//}
}
Change your definition of calculateBoxes() to also take an array that represents the volume of each of the boxes (in your case this will be {50, 20, 5, 1}:
public static void calculateBoxes(int[] ai_ToFill, int[] boxVolumes, int iNumberOfGPS) {
// for each box size
for (int iStepper = 0; iStepper < ai_ToFill.length; iStepper++) {
// while the remaining items to pack is greater than the current box size
while(iNumberOfGPS >= boxVolumes[iStepper]) {
// increment the current box type
ai_ToFill[iStepper]++;
// subtract the items that just got packed
iNumberOfGPS -= boxVolumes[iStepper];
}
}
}
Another way of calculating this (using / and % instead of a while loop) would be:
public static void calculateBoxes(int[] ai_ToFill, int[] boxVolumes, int iNumberOfGPS) {
// for each box size
for (int iStepper = 0; iStepper < ai_ToFill.length; iStepper++) {
if(iNumberOfGPS >= boxVolumes[iStepper]) {
// calculate the number of boxes that could be filled by the items
ai_ToFill[iStepper] = iNumberOfGPS/boxVolumes[iStepper];
// reset the count of items to the remainder
iNumberOfGPS = iNumberOfGPS%boxVolumes[iStepper];
}
}
}

Java make rows and columns

Building a rectangular with character input and specified column and rows. whitespace in the middle.
using standard input for string s, int r, int c
private static void printstuff(String s, int r, int c) {
colums(s, c);
rows(s, c, r);
colums(s, c);
}
// straight columns
private static void colums(String cs, int cc) {
for (int i = 1; i <= cc; i++) {
System.out.print(cs);
}
}
this creates desired whitespace or "" to concat string with ie making
x""""""""x
private static String whitespace(int wc) {
String ws = " ";
for (int i = 1; i <= wc - 3; i++) {
ws += " ";
}
return ws;
}
whitespace to built a rectangular.
// downwards building
private static void rows(String rs, int rc, int rr) {
String ws = whitespace(rc);
for (int i = 1; i <= rr - 1; i++) {
System.out.println(rs + ws + rs);
// put strings together
}
}
}
whitespace and character rows to built a rectangular. needless to say it failed.
sample output:
XXXX X
X X
xxxx
desired output:
xxxx
x x
xxxx
one quick solution below.. Cheers
public class Main {
public static void main(String[] args) {
String s = "X";
int totalColumns = 4;
int totalRow = 3;
colums(s, totalColumns);
rows(s, totalColumns, totalRow);
colums(s, totalColumns);
}
private static void colums(String cs, int cc) {
for (int i = 0; i < cc; i++) {
System.out.print(cs);
}
}
private static String whitespace(int tc) {
String ws = " ";
for (int i = 1; i < tc - 2; i++) {
ws += " ";
}
return ws;
}
private static void rows(String rs, int tc, int tr) {
System.out.println();
for (int i = 0; i < tr - 2 ; i++) {
System.out.println(rs + whitespace(tc) + rs);
}
}
}
Im not sure if this what you want but throw a System.out.println(""); after the for loop in colums

Categories

Resources