2d array of type Space - arrays

I'm trying to make a 9x9 grid of Spaces with 1-10 int values. I'm using the java n-ide app, and am getting a successful compilation, but it's not printing any values.
class Space {
int one = 1;
int two = 2;
...
int ten = 10;
}
class green {
Space[][] board = new Space[9][9];
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[i].length; j++) {
board[i][j] = new Space();
System.out.println(board[i][j].one);
}
}
}

I think you can just refactor your Space class to just hold a primitive integer value:
class Space {
private int value;
private static final String MSG = "Space values must be between 1 and 10 inclusive";
public Space() { }
public Space(int value) {
// prevent spaces from being created with illegal values
if (value < 1 || value > 10) {
throw new IllegalArgumentException(MSG);
}
this.value = value;
}
public int getValue() {
return value;
}
}
Then, in your consuming class, use the Space class:
class Green {
private Space[][] board = new Space[9][9];
for (int i=0; i < board.length; i++) {
for (int j=0; j < board[i].length; j++) {
// maybe get a value from somewhere and use it below
board[i][j] = new Space();
}
}
}
Regarding your exact question about values not printing, the bigger problem than above is that you don't have any logic for assigning values.

Related

Need help on solving this Arrays problem using java

Make an array of integer (score) with 10 members. Randomize the
content with value between 0-100. For each of the member of array,
visualize the value using “-” for each ten. For example: score[0] = 55 will be visualized as “-----" (Using Java).
public class w9lab1 {
public static void main(String args[]) {
double[] temperature = new double[7];
for (int i = 0; i < 7; i++) {
temperature[i] = Math.random()*100;
}
for (int i = 0; i < 7; i++) {
System.out.println(temperature[i]);
}
double totalTemperature = 0;
for (int i = 0; i < 7 ; i++) {
totalTemperature += temperature[i];
}
double maxTemperature = temperature[0];
for (int i = 1; i < 7; i++){
if (temperature[i] > maxTemperature){
maxTemperature = temperature[i];
}
}
System.out.println("Temperatur maximum adalah " + maxTemperature);
}
}
import java.util.Random;
import java.util.Arrays;
public class w9lab1 {
public static void main(String[] args) {
Random random = new Random();
int[] score = new int[10];
for (int i = 0; i < score.length; i++) {
score[i] = random.nextInt(101);
for (int n = 1; n <= score[i] / 10; n++)
System.out.print('-');
System.out.println();
}
System.out.println(Arrays.toString(score));
}
}

gridview dataitem to decimal array

enter code hereHello I try to convert the dataitem into decimal array, here is my code;
if (e.Row.RowType == DataControlRowType.DataRow)
{
for (; i < 9; )
{
if (!DBNull.Value.Equals(DataBinder.Eval(e.Row.DataItem, headerNames[i])))
TotalSales += Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, headerNames[i]));
totals(e.Row.DataItem);
}
}
}
public static decimal[] totals(object arr)
{
decimal[] res = arr as decimal[];
decimal[] sRes = res.OfType<decimal>().ToArray();
return sRes;
}
I can see that the dataitem successfully assigned to arr.
However the line
decimal[] res = arr as decimal[]; does not assign the arr to res, so the next line gives me an error complaining the value cannot be null.
Can you please help?
While I was waiting for an answer here, I tried and came up with a code that calculates totals in GridView_DataBound event, please comment if there is anything can be better and how to not show the total (0.0) under the columns that do not have decimal values (i.e. string)
public static void gridViewTotals1(object sender , EventArgs e)
{
var grdview = (GridView)sender;
decimal[,] rowAndColumns = new decimal[grdview.Rows.Count, grdview.Columns.Count];
decimal n;
decimal[] totalSalesArray = new decimal[grdview.Columns.Count];
for (int i = 0; i < grdview.Columns.Count; i++)
{
for (int j = 0; j < grdview.Rows.Count; j++)
if (decimal.TryParse(grdview.Rows[j].Cells[i].Text, out n))
{
rowAndColumns[j, i] = Convert.ToDecimal(grdview.Rows[j].Cells[i].Text);
}
}
GridViewRow footerRow = grdview.FooterRow;
for (int k = 0; k < grdview.Columns.Count; k++)
{
decimal totalSales = 0;
for (int l = 0; l < grdview.Rows.Count; l++)
{
totalSales += rowAndColumns[l, k];
totalSalesArray[k] = totalSales;
footerRow.Cells[k].Text = String.Format("{0:N2}", totalSales);
}
}
}

Null Pointer Exception in array passed class

So I have a project that requires a generic class that extends Number and also finds the largest and smallest value in the array, the average of all the values, and the size of the array. This seems easy enough to implement, but I have a problem before even putting the generic part of this in place, I get a runtime error of Null Pointer Exception at x.length, regardless of which method I call, always in the same place.
import java.util.Comparator;
public class test
{
public int x[];
public test(int x[])
{
}
public void setx(int newx[])
{
x = newx;
}
public int[] getx()
{
return x;
}
public int findSmallest()
{
int i = 0;
int temp = x[i];
while (i < x.length)
{
i++;
if(x[i] < temp)
{
temp = x[i];
}
else
{
}
}
return temp;
}
public int findLargest()
{
int i = 0;
int temp = x[i];
while (i < x.length)
{
i++;
if(x[i] > temp)
{
temp = x[i];
}
else
{
}
}
return temp;
}
public double findMean()
{
int i = 0;
double sum = 0.0;
double avg = 0.0;
while (i < x.length)
{
sum += x[i];
i++;
}
avg = sum / x.length;
return avg;
}
public int findTotal()
{
int i = x.length;
return i;
}
public static void main (String args[])
{
int[] ia = {1, 2, 3, 4, 5, 6};
test intTest = new test(ia);
System.out.println(intTest.findTotal());
}
}
Any help on how to fix this would be amazing.
You forgot use the setx method in the constructor. You're passing the integer array to constructor but not actually initializing the integer array inside the class. You can do this by calling the setx method in your constructor and passing the integer array x to setx method.
Hope this helps.

Customizing TwoDArrayWritable in Hadoop and Not able to iterate the same in reducer

Trying to emit 2 double dimensional array as value from mapper.
In hadoop we have TwoDArrayWritable which takes 1 - 2D array as input.
In order to achieve my usecase, I tried to edit TwoDArrayWritable to take input of 2 - 2D array
/**
* A Writable for 2D arrays containing a matrix of instances of a class.
*/
public class MyTwoDArrayWritable implements Writable {
private Class valueClass;
private Writable[][] values;
private Class valueClass1;
private Writable[][] values1;
public MyTwoDArrayWritable(Class valueClass,Class valueClass1) {
this.valueClass = valueClass;
this.valueClass1 = valueClass1;
}
public MyTwoDArrayWritable(Class valueClass, DoubleWritable[][] values,Class valueClass1, DoubleWritable[][] values1) {
this(valueClass, valueClass1);
this.values = values;
this.values1 = values1;
}
public Object toArray() {
int dimensions[] = {values.length, 0};
Object result = Array.newInstance(valueClass, dimensions);
for (int i = 0; i < values.length; i++) {
Object resultRow = Array.newInstance(valueClass, values[i].length);
Array.set(result, i, resultRow);
for (int j = 0; j < values[i].length; j++) {
Array.set(resultRow, j, values[i][j]);
}
}
return result;
}
/**
* #return the valueClass
*/
public Class getValueClass() {
return valueClass;
}
/**
* #param valueClass the valueClass to set
*/
public void setValueClass(Class valueClass) {
this.valueClass = valueClass;
}
/**
* #return the values
*/
public Writable[][] getValues() {
return values;
}
/**
* #param values the values to set
*/
public void setValues(DoubleWritable[][] values,DoubleWritable[][] values1) {
this.values = values;
this.values = values1;
}
/**
* #return the valueClass1
*/
public Class getValueClass1() {
return valueClass1;
}
/**
* #param valueClass1 the valueClass1 to set
*/
public void setValueClass1(Class valueClass1) {
this.valueClass1 = valueClass1;
}
/**
* #return the values1
*/
public Writable[][] getValues1() {
return values1;
}
public void readFields(DataInput in) throws IOException {
// construct matrix
values = new Writable[in.readInt()][];
for (int i = 0; i < values.length; i++) {
values[i] = new Writable[in.readInt()];
}
// construct values
for (int i = 0; i < values.length; i++) {
for (int j = 0; j < values[i].length; j++) {
Writable value; // construct value
try {
value = (Writable) valueClass.newInstance();
} catch (InstantiationException e) {
throw new RuntimeException(e.toString());
} catch (IllegalAccessException e) {
throw new RuntimeException(e.toString());
}
value.readFields(in); // read a value
values[i][j] = value; // store it in values
}
}
}
public void write(DataOutput out) throws IOException {
out.writeInt(values.length); // write values
for (int i = 0; i < values.length; i++) {
out.writeInt(values[i].length);
}
for (int i = 0; i < values.length; i++) {
for (int j = 0; j < values[i].length; j++) {
values[i][j].write(out);
}
}
}
}
And emited 2 2D double array from mapper.
MyTwoDArrayWritable array = new MyTwoDArrayWritable (DoubleWritable.class,DoubleWritable.class);
DoubleWritable[][] myInnerArray = new DoubleWritable[EtransEkey.length][EtransEkey[0].length];
DoubleWritable[][] myInnerArray1 = new DoubleWritable[EtransDevalue.length][EtransDevalue[0].length];
// set values in myInnerArray
for (int k1 = 0; k1 < EtransEkey.length; k1++) {
for(int j1=0;j1< EtransEkey[0].length;j1++){
myInnerArray[k1][j1] = new DoubleWritable(EtransEkey[k1][j1]);
}
}
for (int k1 = 0; k1 < EtransDevalue.length; k1++) {
for(int j1=0;j1< EtransDevalue[0].length;j1++){
myInnerArray1[k1][j1] = new DoubleWritable(EtransDevalue[k1][j1]);
}
}
array.set(myInnerArray,myInnerArray1);
Showing error in array.set(myInnerArray,myInnerArray1);
/*
* The method set(DoubleWritable[][], DoubleWritable[][]) is undefined for the type MyTwoDArrayWritableritable
*/
EDIT: How to iterate through these values in Reducer to get myInnerArray matrix and myInnerArray1 matrix?
So far what I did is
for (MyTwoDArrayWritable c : values) {
System.out.println(c.getValues());
DoubleWritable[][] myInnerArray = new DoubleWritable[KdimRow][KdimCol];
for (int k1 = 0; k1 < KdimRow; k1++) {
for(int j1=0;j1< KdimCol;j1++){
myInnerArray[k1][j1] = new DoubleWritable();
}
}
But how to store them back to a double array?
You have not defined the set method in MyTwoDArrayWritable, that is why that error is shown. Instead of calling array.set, you should use the method you have already defined which does exactly what you need: setValues, so replace
array.set(myInnerArray,myInnerArray1);
with
array.setValues(myInnerArray,myInnerArray1);

TicTacToe Array. Winner method and is square free

I dont know what I'm doing wrong here.
Can anyone tell me what's wrong with my checkRow code in checkWinner and isSquareFree method?
Here's my code:
public class TicTacToe
{
/**
* intance variables to hold the data's state for the game.
*/
public static final int GRIDSIZE = 3;
public static final char BLANK = ' ';
public static final char TIE = 'T';
public static final char NOUGHT = 'O';
public static final char CROSS = 'X';
private char[][] grid;
private char WhoseTurn;
/**
* Construct a tic tac toe grid ready to play a new game.
* The game grid should be GRIDSIZE by GRIDSIZE spaces
* all containing the BLANK character.
* Initially, the starting player is not decided,
* indicated by setting whoseturn as BLANK.
*/
public TicTacToe()
{
this.WhoseTurn = BLANK;
this.grid = new char[GRIDSIZE][GRIDSIZE];
for (int r = 0; r < grid.length; r++)
{
for ( int c = 0; c < grid[r].length; c++)
{
this.grid[r][c] = BLANK;
}
}
}
/**
* Reset the tic tac toe game ready to play again.
* Conditions for play are the same as for the constructor.
*/
public void newGame()
{
char[][] boardToClear = getGrid();
final int sizeOfBoard = grid.length;
for ( int row = 0; row < grid.length; row++)
{
for ( int col = 0; col < grid.length; col++)
{
grid[row][col] = BLANK;
}
}
}
public char[][] getGrid()
{
int gridLen = grid.length;
char[][] gridCopy = new char[gridLen][];
for ( int r = 0; r < gridCopy.length; r++)
{
gridCopy[r] = new char[gridCopy.length];
for ( int c = 0; c < gridCopy.length; c++)
{
gridCopy[r][c] = grid[r][c];
}
}
return gridCopy;
}
public char getWhoseTurn()
{
return WhoseTurn;
}
/**
* printGrid() displays the current state of the game grid
* on the console for debugging.
* It uses the form feed character \u000C to clear the console before
* printing the current grid.
*/
private void printGrid()
{
System.out.print('\u000C'); // clear the console window
for (int x = 0; x < GRIDSIZE-1; x++) {
System.out.print(grid[x][0] + "|" +
grid[x][1] + "|" + grid[x][2]);
System.out.println("\n-----"); //
System.out.print(grid[GRIDSIZE-1][0] + "|" +
grid[GRIDSIZE-1][1] + "|" +
grid[GRIDSIZE-1][2]);
}
}
// Now print last row (with no bottom edge)
private boolean checkIfGridFull()
{
char[][] board = getGrid();
int size = grid.length;
for ( int row = 0; row < size; row++)
{
for ( int col = 0; col < board[row].length; col++)
{
if ( grid[row][col] == BLANK)
{
return false;
}
}
}
return true;
}
public boolean move(char player, int row, int col)
{
char[][] boardToPlay = getGrid();
int size = grid.length;
char x = player;
if ( (player == NOUGHT) || ( player == CROSS))
{
if ( (x == WhoseTurn) || (WhoseTurn == BLANK))
{
if ((checkIfGridFull() == false) && ( boardToPlay[row][col] == BLANK))
{
if( (row < size) && ( col < size))
{
boardToPlay[row][col] = player;
if ( player == CROSS)
{
WhoseTurn = NOUGHT;
}
if ( player == NOUGHT)
{
WhoseTurn = CROSS;
}
return true;
}
}
}
}
return false;
}
public boolean isSquareFree( int row, int col)
{
if ((grid[row][col] == BLANK))
{
return true;
}
return false
;
}
public char checkWinner()
{
int countNought;
int countCross ;
int size = grid.length;
for ( int row = 0; row < size; row++)
{
countNought = 0;
countCross = 0;
for ( int col = 0; col < size; col++)
{
if ( grid[row][col] == CROSS)
{
countCross++;
}
if ( grid[row][col] == NOUGHT)
{
countNought++;
}
if ( countNought == size)
{
return NOUGHT;
}
if ( countCross == size)
{
return CROSS;
}
}
}
return BLANK;
}
}
One good method for tracking down a bug in a project like this is to use print line statements. Try this: put a print line somewhere near where you think the problem is, and print out the values of some of the local variables. If you see values that you shouldn't then you know that your data has come into some trouble earlier on in the code. In that case, move the print lines further back in the flow and try again. Keep doing this until you notice values going from good to bad (or bad to good): at that point you have tracked down the code that contains the bug.
Once you've done this, you will usually have only a small function to think about, and it will be much easier to understand what you've done wrong. If you still can't find the problem, then post the code snippet here and someone will probably be able to help you.
checkWinner() is wrong you're not checking diagonals, just write the eights winning combinations

Resources