Related
I would like to create a 2d Array with Java, or a Matrix with a int numbers.
I've already did that..but I still don't know how to assign labels to the rows/columns.
I would like to be able to access any number inside the matrix based on the row/columns
This is my java code
Gson gson = new Gson();
int[][] data = {{78, 0, 0, 0, 0}, {0, 54, 0, 0, 0}, {0, 0, 12, 0, 0}, {0, 0, 0, 74, 0}, {0, 0, 0, 0, 11}};
String json = gson.toJson(data);
// Convert JSON string into multidimensional array of int.
int[][] dataHeatMap = gson.fromJson(json, int[][].class);
for (int[] i : dataHeatMap) {
for (int j : i) {
System.out.print(j + " ");
}
System.out.println("");
}
return json;
You can use Enums:
public enum ROW {a, b, c, d, e}
public enum COL {f, g, h, i, j}
data[ROW.a.ordinal()][COL.f.ordinal()] = 3;
Use ENUM types which does represend the special index of your 2dim Array. Give them a field called value/name/... and create them with the index of them in the array. Afterwards you can easy call them with getting their letter-value which does represent the array index.
It´s very readable and ENUM.<VALUE> does not represent an INT value. So this is the way how you can do it.
public enum ROW {
A(0), B(1), C(2), D(3), E(4);
private final int value;
ROW(int value) { this.value = value; }
public int getValue() { return value; }
}
public enum COL {
F(0), G(1), H(2), I(3), J(4);
private final int value;
COL(int value) { this.value = value; }
public int getValue() { return value; }
}
public static void main(String []args){
int[][] matrix = {{78, 0, 0, 0, 0}, {0, 54, 0, 0, 0}, {0, 0, 12, 0, 0}, {0, 0, 0, 74, 0}, {0, 0, 0, 0, 11}};
System.out.println("Value: " + matrix[ROW.A.getValue()][COL.F.getValue()]);
}
I would prefer the way above because you see what directly happens and can assign any value you want. But you just can use ENUM.ordinal(), too.
Then data[ROW.a.ordinal()][...] will return 0 for ROW because it´s listed first. b will return 1,... It just depends on the way they are listed/created on the ENUM.
I have input like this:
0, 0, 0, 0, 1, 0, 2, A
0, 0, 3, 0, 1, 0, 2, A
0, 2, 0, 0, 1, 0, 2, B
0, 0, 0, 0, 1, 0, 2, A
With the letter being the label, and then numbers being the inputs.
I'd like to store this whole matrix in one data structure, such that the inputs that correspond to a particular label can be associated with it.
How to do this?
With a 2d array?
With an array list?
Hashmap?
If you want to use A, B,... as keys, than you can use a HashMap with string as keys and arraylist as values
Map<String, List<String>> map = new HashMap<String, List<String>>();
Then you can iterate over your input and check if the map already contains the key.
for (...) {
...
if (!map.containsKey(key)) {
map.put(key, new ArrayList<String>());
}
map.get(key).add(value);
}
This is a generic example and you can do modifications based on your requirements.
If you need your int array just replace the following code:
import java.util.ArrayList;
class Group {
public String key;
public String value;
public String getKey() {
return key;
}
public String getValue() {
return value;
}
Group(String v, String k) {
this.key = k;
this.value = v;
}
#Override
public String toString() {
return this.key + " " + this.value;
}
}
public class Datastructure {
public static void main(String[] args) {
ArrayList<Group> list = new ArrayList<>();
list.add(new Group("0, 0, 0, 0, 1, 0, 2", "A"));
list.add(new Group("0, 0, 3, 0, 1, 0, 2", "A"));
list.add(new Group("0, 2, 0, 0, 1, 0, 2", "B"));
list.add(new Group("0, 0, 0, 0, 1, 0, 2", "A"));
findKeyList(list, "A");
}
public static void findKeyList(ArrayList<Group> list, String search) {
if (!list.isEmpty()) {
for (Group element : list) {
if (element.getKey().equals(search)) {
System.out.println(element.toString());
}
}
}
}
}
HashMap is not a good solution for your case since there is no uniqueness in any of the attributes. Create a classwith 2 attributes:
Class Obj {
char[] array;
String label;
}
Then maintain a list of these objects as ArrayList
You can use a HashMap :
Map<char, String[][]> matrix = new HashMap<char, String[]>();
matrix.put('A', new String[][]{{0, 0, 0, 0, 1, 0, 2}, {0, 0, 3, 0, 1, 0, 2}, ...});
......
This way, many arrays could be associated with a single label (or character).
I have to write code that takes in 4 parameters (row of a tic-tac-toe board, column, the row increment, and the column increment) which is to move through the tic-tac-toe board and return the highest sequence of the symbol inside of the row and column given.
I have it mostly working, except I know that my code is faulty in that it cannot distinguish between instances where it should return 2 vs 3 (it returns 2 rather than 3), but after a solid day of trying every possible thing I could think of, most of my attempted fixes only made it more complex while causing the test to return an out of bounds exception error.
Can somebody please offer some advice as to how I could go about fixing this?
public int getMaxSequence(int row, int column, int dr, int dc, char symbol) {
int maxSequence = 0;
List<Integer> sequence = new ArrayList<Integer>();
sequence.add(0);
for (int i = row, j = column; i <getBoard().length-1 && j < getBoard()[i].length-1; i = i+dr, j = j + dc){
if (this.board[i][j].getSymbol()== symbol && this.board[i+dr][j+dc].getSymbol()!= symbol){
sequence.add(1);
}
else if (this.board[i][j].getSymbol()== symbol && this.board[i+dr][j+dc].getSymbol()== symbol){
sequence.add(2);
}
else if (this.board[i][j].getSymbol()== symbol && this.board[i+dr][j+dc].getSymbol()== symbol
&& this.board[i+dr+dr][j+dc+dc].getSymbol()== symbol){
sequence.add(3);
}
maxSequence = Collections.max(sequence);
if (isWithinBounds( row+dr, column+dc)!=true){
return Collections.max(sequence);}
}
return Collections.max(sequence);
}
}
Here is the test (line 144 marked by /*->*/ is the obstacle thus far, since 3 is expected):
public class TicTacToe5x5Tests extends TestCase {
// Piece is an immutable class so it is okay to make these constants
// Do not make static final pieces in your tests if they are mutable
public static final Piece X = new Piece('x');
public static final Piece O = new Piece('o');
public static final Piece E = new EmptyPiece();
public static final Piece B = new BlockedPiece();
public static TicTacToe5x5Game createStartGame() {
// uses the make start game method on TicTacToe5x5Game
return TicTacToe5x5Game.makeStartGame('o', 'x');
}
public static TicTacToe5x5Game createMidGame1() {
// an example board after 2 turns each (score 1 for x, 2 for o)
Piece[][] board =
{{X, E, E, E, E},
{E, E, E, E, O},
{E, E, B, O, E},
{X, E, E, E, E},
{E, E, E, E, E}};
return new TicTacToe5x5Game(board, 'o', 'x');
}
public static TicTacToe5x5Game createMidGame2() {
// an example board mid-game (score 2 for x, 3 for o)
Piece[][] board =
{{X, O, O, E, X},
{X, E, O, E, O},
{E, E, B, O, E},
{X, O, X, X, E},
{E, O, X, E, E}};
return new TicTacToe5x5Game(board, 'o', 'x');
}
public static TicTacToe5x5Game createEndGame1() {
// an example board where player x has won (score 4 for x, 3 for o)
Piece[][] board =
{{X, O, O, E, X},
{X, E, O, E, O},
{X, E, B, O, E},
{X, O, X, X, E},
{E, E, E, E, E}};
return new TicTacToe5x5Game(board, 'o', 'x');
}
public static TicTacToe5x5Game createEndGame2() {
// an example board where nobody has won (score 3 for x, 3 for o) but there are no more moves
Piece[][] board =
{{X, O, O, O, X},
{O, O, O, X, O},
{X, X, B, O, X},
{X, O, X, X, X},
{O, X, O, O, X}};
return new TicTacToe5x5Game(board, 'o', 'x');
}
public static PlacePieceAction createAction() {
// won't be valid for all TicTacToeGame states, but just an example
return new PlacePieceAction('x', 2, 1);
}
public void test_changeTurn() {
TicTacToe5x5Game game = createStartGame();
assertEquals('x', game.getNotTurn());
assertEquals('o', game.getTurn());
game.changeTurn();
assertEquals('x', game.getTurn());
assertEquals('o', game.getNotTurn());
}
public void test_PlacePieceAction() {
PlacePieceAction action1 = new PlacePieceAction('o', 3, 1);
PlacePieceAction action2 = new PlacePieceAction('o', 2, 2);
PlacePieceAction action3 = new PlacePieceAction('x', 3, 0);
// use the initial state from TicTacToe5x5
TicTacToe5x5Game game0 = createStartGame();
assertTrue(action1.isValid(game0)); // it is o's turn
assertFalse(action2.isValid(game0)); // middle square is not usable by either player
assertFalse(action3.isValid(game0)); // it is not x's turn
// test that performing action1 will put an O at 3, 1
action1.update(game0);
assertEquals('x', game0.getTurn());
Piece[][] expectedBoard1 =
{{E, E, E, E, E},
{E, E, E, E, E},
{E, E, B, E, E},
{E, O, E, E, E},
{E, E, E, E, E}};
assertTrue(Arrays.deepEquals(expectedBoard1, game0.getBoard()));
// test that performing action3 will put an X at 3, 0
assertTrue(action3.isValid(game0)); // it is o's turn now so this is ok
action3.update(game0);
assertEquals('o', game0.getTurn());
Piece[][] expectedBoard2 =
{{E, E, E, E, E},
{E, E, E, E, E},
{E, E, B, E, E},
{X, O, E, E, E},
{E, E, E, E, E}};
assertTrue(Arrays.deepEquals(expectedBoard2, game0.getBoard()));
}
public void test_hasEmptySpace() {
assertTrue(createStartGame().hasEmptySpace());
assertTrue(createMidGame1().hasEmptySpace());
assertTrue(createEndGame1().hasEmptySpace());
assertFalse(createEndGame2().hasEmptySpace());
}
public void test_getMaxSequence() {
TicTacToe5x5Game game = createMidGame2();
// test row 0
assertEquals(2, game.getMaxSequence(0, 0, 0, 1, 'o'));
assertEquals(1, game.getMaxSequence(0, 0, 0, 1, 'x'));
// test row 3
assertEquals(1, game.getMaxSequence(3, 0, 0, 1, 'o'));
assertEquals(2, game.getMaxSequence(3, 0, 0, 1, 'x'));
// test column 0
assertEquals(0, game.getMaxSequence(0, 0, 1, 0, 'o'));
assertEquals(2, game.getMaxSequence(0, 0, 1, 0, 'x'));
// test column 1
assertEquals(2, game.getMaxSequence(0, 1, 1, 0, 'o'));
assertEquals(0, game.getMaxSequence(0, 1, 1, 0, 'x'));
// test down-right diagonal 1,0
assertEquals(0, game.getMaxSequence(1, 0, 1, 1, 'o'));
assertEquals(1, game.getMaxSequence(1, 0, 1, 1, 'x'));
// test down-right diagonal 0,1
/*->*/ assertEquals(3, game.getMaxSequence(0, 1, 1, 1, 'o'));
assertEquals(0, game.getMaxSequence(0, 1, 1, 1, 'x'));
// test down-left diagonal 1,4
assertEquals(2, game.getMaxSequence(1, 4, 1, -1, 'o'));
assertEquals(1, game.getMaxSequence(1, 4, 1, -1, 'x'));
// test down-left diagonal 2,4
assertEquals(0, game.getMaxSequence(2, 4, 1, -1, 'o'));
assertEquals(2, game.getMaxSequence(2, 4, 1, -1, 'x'));
// test middle square (it is not a free square, it is blocked)
assertEquals(2, game.getMaxSequence(0, 2, 1, 0, 'o'));
assertEquals(2, game.getMaxSequence(0, 2, 1, 0, 'x'));
assertEquals(1, game.getMaxSequence(2, 0, 0, 1, 'o'));
assertEquals(0, game.getMaxSequence(2, 0, 0, 1, 'x'));
assertEquals(0, game.getMaxSequence(0, 0, 1, 1, 'o'));
assertEquals(1, game.getMaxSequence(0, 0, 1, 1, 'x'));
assertEquals(1, game.getMaxSequence(0, 4, 1, -1, 'o'));
assertEquals(1, game.getMaxSequence(0, 4, 1, -1, 'x'));
}
public void test_getScore() {
assertEquals(0, createStartGame().getScore('x'));
assertEquals(0, createStartGame().getScore('o'));
assertEquals(1, createMidGame1().getScore('x'));
assertEquals(2, createMidGame1().getScore('o'));
assertEquals(2, createMidGame2().getScore('x'));
assertEquals(3, createMidGame2().getScore('o'));
assertEquals(4, createEndGame1().getScore('x'));
assertEquals(3, createEndGame1().getScore('o'));
assertEquals(3, createEndGame2().getScore('x'));
assertEquals(3, createEndGame2().getScore('o'));
}
public void test_isWinner() {
assertFalse(createStartGame().isWinner('x'));
assertFalse(createStartGame().isWinner('o'));
assertFalse(createMidGame1().isWinner('x'));
assertFalse(createMidGame1().isWinner('o'));
assertFalse(createMidGame2().isWinner('x'));
assertFalse(createMidGame2().isWinner('o'));
assertTrue(createEndGame1().isWinner('x'));
assertFalse(createEndGame1().isWinner('o'));
assertFalse(createEndGame2().isWinner('x'));
assertFalse(createEndGame2().isWinner('o'));
}
public void test_isEnd() {
assertFalse(createStartGame().isEnd());
assertFalse(createMidGame1().isEnd());
assertFalse(createMidGame2().isEnd());
assertTrue(createEndGame1().isEnd());
assertTrue(createEndGame2().isEnd());
}
public void test_AI_getAllValidActions() {
TicTacToe5x5Game game0 = createStartGame();
TicTacToe5x5AI ai = new TicTacToe5x5AI("o");
List<Action<TicTacToe5x5Game>> actions = ai.getAllValidActions(game0);
// check to make sure at least all empty space moves are in there
int missingMoves = 0;
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
if (game0.getBoard()[i][j] instanceof EmptyPiece) {
boolean found = false;
for (Action<TicTacToe5x5Game> action : actions) {
PlacePieceAction ppa = (PlacePieceAction)action;
if (ppa.getRow() == i && ppa.getColumn() == j) {
found = true;
}
}
if (!found) {
missingMoves++;
}
}
}
}
assertEquals(0, missingMoves); // should be 0 missing moves
}
public void test_AI_getHeuristicScore() {
TicTacToe5x5Game game0 = createMidGame2();
TicTacToe5x5AI aiO = new TicTacToe5x5AI("o");
TicTacToe5x5AI aiX = new TicTacToe5x5AI("x");
// score of mid game 2 is 3 for player o. If player o plays at 3, 4
// then they would win with a score of 4
assertEquals(4.0, aiO.getHeuristicScore(new PlacePieceAction('o', 3, 4), game0));
// score should still be 3. if this is 4 then your heuristic is mutating
// the board and not properly undoing its mutation.
assertEquals(3.0, aiO.getHeuristicScore(new PlacePieceAction('o', 2, 4), game0));
// change the turn so if the AI is checking for validity of the action the test
// will still work
game0.changeTurn();
// score of mid game 2 is 2 for player x. However, if player x plays at 2, 0
// then they would win with a score of 4
assertEquals(4.0, aiX.getHeuristicScore(new PlacePieceAction('x', 2, 0), game0));
// score should still be 2. if this is 5 then your heuristic is mutating
// the board and not properly undoing its mutation.
System.out.println(game0);
assertEquals(2.0, aiX.getHeuristicScore(new PlacePieceAction('x', 4, 0), game0));
}
public void test_AI_getBestAction() {
// check to see if on board 2 they will make the move that will win the game
TicTacToe5x5Game game0 = createMidGame2();
TicTacToe5x5AI ai = new TicTacToe5x5AI("o");
PlacePieceAction ppa = (PlacePieceAction)ai.getBestAction(game0);
assertEquals(3, ppa.getRow());
assertEquals(4, ppa.getColumn());
}
public static void main(String[] args) {
// print some games and sample actions
System.out.println(createStartGame());
System.out.println(createMidGame2());
System.out.println(createEndGame2());
System.out.println(createAction());
}
}
You're getting an IndexOutOfBoundsException because you are only testing the top half of the range in your loop test:
for (int i = row, j = column;
i <getBoard().length-1 && j < getBoard()[i].length-1;
i = i+dr, j = j + dc)
You allow negative increments, e.g:
assertEquals(2, game.getMaxSequence(1, 4, 1, -1, 'o'));
Therefore you need to check that the index is greater than or equal to zero or you will get an exception when the index decreases to -1.
for (int i = row, j = column;
i >= 0 && j >= 0 && i < getBoard().length && j < getBoard()[i].length;
i += dr, j += dc)
Also, the upper range check should be less than the length or less than or equal to the length minus one, but not less than the length minus one or you will exclude the last element.
... in particular when modifying the underlying items?
Below is a quick example that selects a range and adds an item above the selection for TableView and ListView. The selectedIndices before/after adding:
indices before modification: [2, 3]
indices after modification: [3, 4]
Expected options:
a single wasReplaced for the whole range
a wasRemoved for the "2" and a wasAdded for the "4"
??
Actual:
table's selection fires two events, each with a single wasAdded
list's selection fires a wasPermutated (that's nuts, or what am I missing?)
Output (jdk8u40b12):
Change #0 on TableView indices
list = [3]
Change event data:
class javafx.scene.control.MultipleSelectionModelBase$3
javafx.scene.control.MultipleSelectionModelBase$3#4ececa
cursor = 0
Kind of change: added
Affected range: [0, 1]
Added size: 1
Added sublist: [3]
Change #1 on TableView indices
list = [3, 4]
Change event data:
class javafx.scene.control.MultipleSelectionModelBase$3
javafx.scene.control.MultipleSelectionModelBase$3#b0161d
cursor = 0
Kind of change: added
Affected range: [1, 2]
Added size: 1
Added sublist: [4]
Change #0 on ListView indices
list = [3, 4]
Change event data:
class com.sun.javafx.collections.NonIterableChange$SimplePermutationChange
{ permutated by [4, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0] }
cursor = 0
Kind of change: permutated
Affected range: [0, 2]
Permutation: [0->4, 1->3]
The producing code:
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
import javafx.collections.ListChangeListener.Change;
import javafx.scene.control.ListView;
import javafx.scene.control.SelectionMode;
import javafx.scene.control.TableView;
import javafx.stage.Stage;
public class SelectedIndicesOnItemsModified extends Application {
#Override
public void start(Stage primaryStage) throws Exception {
ObservableList<Integer> items = FXCollections.observableArrayList(1, 2, 3, 4);
TableView<Integer> table = new TableView<>(items);
table.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
table.getSelectionModel().selectRange(2, 4);
System.out.println("indices before modification: " +
table.getSelectionModel().getSelectedIndices());
ListView<Integer> list = new ListView<>(items);
list.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
list.getSelectionModel().selectRange(2, 4);
new PrintingListChangeListener("TableView indices ",
table.getSelectionModel().getSelectedIndices());
new PrintingListChangeListener("ListView indices ",
list.getSelectionModel().getSelectedIndices());
items.add(0, 111);
}
public static void main(String[] args) {
launch(args);
}
public static <T> void prettyPrint(Change<? extends T> change) {
StringBuilder sb = new StringBuilder("\tChange event data:\n");
sb.append("\n " + change.getClass() + "\n " + change);
int i = 0;
change.reset();
while (change.next()) {
sb.append("\n\tcursor = ").append(i++).append("\n");
final String kind = change.wasPermutated() ? "permutated" : change
.wasReplaced() ? "replaced"
: change.wasRemoved() ? "removed"
: change.wasAdded() ? "added"
: change.wasUpdated() ? "updated" : "none";
sb.append("\t\tKind of change: ").append(kind).append("\n");
sb.append("\t\tAffected range: [").append(change.getFrom())
.append(", ").append(change.getTo()).append("]\n");
if (kind.equals("added") || kind.equals("replaced")) {
sb.append("\t\tAdded size: ").append(change.getAddedSize())
.append("\n");
sb.append("\t\tAdded sublist: ")
.append(change.getAddedSubList()).append("\n");
}
if (kind.equals("removed") || kind.equals("replaced")) {
sb.append("\t\tRemoved size: ").append(change.getRemovedSize())
.append("\n");
sb.append("\t\tRemoved: ").append(change.getRemoved())
.append("\n");
}
if (kind.equals("permutated")) {
StringBuilder permutationStringBuilder = new StringBuilder("[");
for (int k = change.getFrom(); k < change.getTo(); k++) {
permutationStringBuilder.append(k).append("->")
.append(change.getPermutation(k));
if (k < change.getTo() - 1) {
permutationStringBuilder.append(", ");
}
}
permutationStringBuilder.append("]");
String permutation = permutationStringBuilder.toString();
sb.append("\t\tPermutation: ").append(permutation).append("\n");
}
}
System.out.println(sb.toString());
};
public static class PrintingListChangeListener implements ListChangeListener {
String source;
int counter;
public PrintingListChangeListener() {
}
public PrintingListChangeListener(String message, ObservableList<?> list) {
list.addListener(this);
source = message;
}
#Override
public void onChanged(Change change) {
System.out.println("Change #" + counter++ + " on " +source +
"\nlist = " + change.getList());
prettyPrint(change);
}
}
}
Filed two issues, RT-39393 for ListView, RT-39394 for TableView
A tentative partly answer to my own question
Notification count
Number of notification (aka: calls to changed(Change c)) should be the same as number in underlying data, in pseudo-code
itemsChanges = 0;
itemsListener = c -> itemsChanges++;
getItems().addListener(itemsListener);
selectedChanges = 0;
selectedListener = c -> selectedChanges++;
getSelectedIndices().addListener(selectedListener);
getItems().modifySomehow(...);
assertEquals(itemsChanges, selectedChanges);
Change Types
Thinking about it, most changes in the underlying items seem to map to a replaced in the selectedIndices ("value" below denotes the elements in the selectedIndices):
"real" wasAdded: all values greater than the insertion location must be increased by addedSize
// selectedIndices before
[2, 4]
items.add(0, something);
// selectedIndices after
[3, 5]
-> net effect: two values are set (== replaced by) to a new value
"real" wasRemoved: all values pointing to removed items must be removed as well, values greater than the remove location must be decreased by removedSize
// selectedIndices before
[2, 4, 5, 8]
items.removeAll(items.get(3), items.get(5))
// selectedIndices after
[2, 3, 6]
-> net effect: replace [4, 5, 8] at pos 1 by [3, 6]
wasUpdated: indices are unchanged, though the underlying items did change somehow. Depending on context, it might be a good idea to pass those updates through to its listener or not.
Still open: replaced/permutation in items
To get those expected (at least by my paper coding :-) notifications correct, isn't quite trivial - and went wrong in MultipleSelectionModelBase and subclasses. Currently playing with moving all the nasty details into a dedicated IndicesList (which is-a TransformList with items as sourceList)
I can't seem to figure out what my parameters should be for my method "public static int[][] sellSeatByPrice". I need to prompt the user for a price (of a seat), then figure out if that price is taken (if it = 0) and if not, assign it the value 0.
Below is my code, help please!
import java.util.Scanner;
/**
* Write a description of class A10_TheaterSeating here.
*
* #author (your name)
* #version (a version number or a date)
*/
public class A10_TheaterSeating
{
public static void main(String args[])
{
System.out.println("***Welcome to the Ticket Choice App!***");
System.out.println();
int[][] theaterSeats = //set values in seating chart array
{
{10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
{10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
{10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
{10, 10, 20, 20, 20, 20, 20, 20, 10, 10},
{10, 10, 20, 20, 20, 20, 20, 20, 10, 10},
{10, 10, 20, 20, 20, 20, 20, 20, 10, 10},
{20, 20, 30, 30, 40, 40, 30, 30, 20, 20},
{20, 30, 30, 40, 50, 50, 40, 30, 30, 20},
{30, 40, 50, 50, 50, 50, 50, 50, 40, 30}
};
int[][] seats = theaterSeats;
printArray(seats); //print the seating chart
System.out.println();
//Defining variables
String str = "";
String input = "";
while (!input.equalsIgnoreCase("Q"))
{
System.out.print("Select 'S' to pick a seat, 'P' choose a price or 'Q' to quit: ");
Scanner in = new Scanner(System.in);
input = in.next();
if (input.equalsIgnoreCase("S"))
{
System.out.print("Enter row and seat number desired: ");
int row = in.nextInt();
int seat = in.nextInt();
System.out.println();
sellSeatByNumber(seats, row, seat);
printArray(seats);
System.out.println();
}
else if (input.equalsIgnoreCase("P"))
{
System.out.print("Enter price of seat desired: ");
int price = in.nextInt();
System.out.println();
sellSeatByPrice(seats, row, seat, price);
printArray(seats);
System.out.println();
}
}
System.out.println();
System.out.println("Thank you for choosing the ticket choice app.");
System.out.println();
}
public static void printArray(int[][] currSeat)
{
final int ROWS = 9;
final int COLUMNS = 10;
for(int i = 0; i < ROWS; i++)
{
for (int j = 0; j < COLUMNS; j++)
{
System.out.print(currSeat[i][j] + "\t");
}
System.out.println();
}
}
public static int[][] sellSeatByNumber(int[][] seats, int row, int seat)
{
if (row <= 0 || row > 9)
{
if (seat <= 0 || seat > 10)
{
System.out.print("Please enter a valid row and seat: ");
}
}
if (seats[row][seat] == 0)
{
System.out.print("That seat is taken. Please select another seat: ");
}
else
{
seats[seats.length - row][seat - 1] = 0;
}
return seats;
}
public static int[][] sellSeatByPrice(int[][] seats, int row, int seat, int price)
{
if (seats[row][seat] = price)
{
seats[seats.length - row][seat - 1] = 0;
}
return seats;
}
}
Your parameters seem fine - the internal logic and syntax is incorrect.
Since you're using static methods, and passing along the seat matrix, that is okay - but you have to check that the values being passed in are inside the bounds of your matrix - or you will get exceptions on them.
For instance, you don't check the bounds in sellSeatByPrice(). You really should do that, or a bogus row/seat combination could blow your program up.
It's also the case that the comparison given is incorrect:
if (seats[row][seat] = price)
should really be
if (seats[row][seat] == price)
as = is assignment, and == is primitive comparison.
Furthermore, in sellSeatByNumber(), you can still run into issues since an out of bounds row/seat combo will still blow up. You do check the bounds - kudos - but you don't return anything if they're outside of those bounds. In all reality, an IllegalArgumentException should be raised if they're stepping out of bounds, or you can return the matrix unmodified (which may be more straightforward).