2D ArrayList User Input Determines Size and Output

Page 1 of 1

13 Replies - 10963 Views - Last Post: 14 April 2010 - 07:51 PMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'http://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=167950&amp;s=6cc9266b29dff4f70abee82523bcdf65&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

Reputation: 2
• Posts: 20
• Joined: 05-April 10

2D ArrayList User Input Determines Size and Output

Posted 14 April 2010 - 01:09 AM

I am trying to get an ArrayList generated by user input to be read by scanner and determine whether or not the user input equates to a magic square or not.

Here is my Squares code:

```import java.util.ArrayList;
import java.util.Scanner;

/**
This class tests whether a sequence of inputs forms a magic square.
Xxxx is replaced by student's last name
*/

public class Squares
{
int[][] table;
int[][] square;
int column, sumC;
int row, sumR;
int size;
int sumDiag, sumReverse;

//create new square of g

public Squares(int size)
{
int square[][] = new int [size][size]; // table user defined
}

//return the sum of the values in the given row

public int sumRow(int row)
{
int sumRow = 0;
for(column = 0; column < square.length; column++)
{
sumR = sumR + table[row][column];
}
return sumR;
}

//return the sum of the values in the given column
public int sumCol(int col)
{
int sumC = 0;
for(row = 0; row < size; row++)
{
sumC = sumC + table[row][column];
}
return sumC;
}
//return the sum of the values in the main diagonal
public int sumMainDiag()
{
int sumDiag = 0;for (row = 0, column = square.length - 1; row < square.length; row++)
{
sumDiag += square[row][column];
column --;
}
return sumDiag;
}
//return the sum of the values in the other ("reverse") diagonal
public int sumOtherDiag()
{
int sumReverse = 0;
for (row = square.length-1, column = 0; column < square.length; row--)
{
sumReverse += square[row][column];
column++;
}
return sumReverse;
}
//return true if the square is magic (all rows, cols, and diags have same sum), false otherwise

public boolean isMagic()
{
boolean result = false;
if (sumR == sumC)
if (sumC == sumDiag)
if (sumDiag == sumReverse)
result = true;
return result;
}

//read info into the square from the input stream associated with the
//Scanner parameter
{
for (int row = 0; row < square.length; row++)
for (int col = 0; col < square.length; col ++)
square[row][column] = scan.nextInt();
}
//print the contents of the square, neatly formatted

public void printSquare()
{
for (int row = 0; row < table[row].length; row++)
{
for (int col = 0; col < table[row].length; col++)
System.out.println();
}
}
}

```

This is the "main" code:

```import java.util.ArrayList;
import java.util.Scanner;

/**
This class tests whether a sequence of inputs forms a magic square.
Xxxx is replaced by student's last name
*/

public class Squares
{
int[][] table;
int[][] square;
int column, sumC;
int row, sumR;
int size;
int sumDiag, sumReverse;

//create new square of g

public Squares(int size)
{
int square[][] = new int [size][size]; // table user defined
}

//return the sum of the values in the given row

public int sumRow(int row)
{
int sumRow = 0;
for(column = 0; column < square.length; column++)
{
sumR = sumR + table[row][column];
}
return sumR;
}

//return the sum of the values in the given column
public int sumCol(int col)
{
int sumC = 0;
for(row = 0; row < size; row++)
{
sumC = sumC + table[row][column];
}
return sumC;
}
//return the sum of the values in the main diagonal
public int sumMainDiag()
{
int sumDiag = 0;for (row = 0, column = square.length - 1; row < square.length; row++)
{
sumDiag += square[row][column];
column --;
}
return sumDiag;
}
//return the sum of the values in the other ("reverse") diagonal
public int sumOtherDiag()
{
int sumReverse = 0;
for (row = square.length-1, column = 0; column < square.length; row--)
{
sumReverse += square[row][column];
column++;
}
return sumReverse;
}
//return true if the square is magic (all rows, cols, and diags have same sum), false otherwise

public boolean isMagic()
{
boolean result = false;
if (sumR == sumC)
if (sumC == sumDiag)
if (sumDiag == sumReverse)
result = true;
return result;
}

//read info into the square from the input stream associated with the
//Scanner parameter
{
for (int row = 0; row < square.length; row++)
for (int col = 0; col < square.length; col ++)
square[row][column] = scan.nextInt();
}
//print the contents of the square, neatly formatted

public void printSquare()
{
for (int row = 0; row < table[row].length; row++)
{
for (int col = 0; col < table[row].length; col++)
System.out.println();
}
}
}

```

This is the error message I am getting back:

symbol : constructor Squares(java.util.ArrayList<java.lang.Integer>)
location: class Squares
Squares mySquare = new Squares(numbers);
^
symbol : variable count
System.out.println("\n******** Square " + count + " ********");
^
2 errors

----jGRASP wedge: exit code for process is 1.
----jGRASP: operation complete.

Can anyone help with this. I am trying to get the ArrayList to be built by the user input, then read by the program, and determined to be or not be a magic square or not a square at all. Also, I want to restrict the program to not crashing if something other than an Integer or "Q" is input by the user. i want it to have an exit statement but I'm not sure how I would construct that or where to include.

Thanks for any help that can be provided!

Is This A Good Question/Topic? 0

Replies To: 2D ArrayList User Input Determines Size and Output

#2 citus

Reputation: 16
• Posts: 140
• Joined: 28-March 10

Re: 2D ArrayList User Input Determines Size and Output

Posted 14 April 2010 - 02:25 AM

You posted the "Squares" class twice, please post main code.

#3 Dogstopper

Reputation: 2965
• Posts: 11,222
• Joined: 15-July 08

Re: 2D ArrayList User Input Determines Size and Output

Posted 14 April 2010 - 03:29 AM

These errors are simple. LEt me explain:
```symbol  : constructor Squares(java.util.ArrayList<java.lang.Integer>)
location: class Squares
Squares mySquare = new Squares(numbers);
^
symbol  : variable count
System.out.println("\n******** Square " + count + " ********");
^

```

Though i cannot actually see the code, I can infer these guesses.

The first error indicates that you are trying to pass an array of Integers into the Squares constructor, which merely takes a size. You will have to make that constructor.

As for your second error, that means that count cannot be accessed by that method. It usually means that count was declared in another method and so cannnot be accessed here. Read my tutorial on scope:
http://www.dreaminco...topic158726.htm

Reputation: 2
• Posts: 20
• Joined: 05-April 10

Re: 2D ArrayList User Input Determines Size and Output

Posted 14 April 2010 - 07:42 AM

Oops!
Here is the main.

```import java.util.ArrayList;
import java.util.Scanner;

/**
This class tests whether a sequence of inputs forms a magic square.
Xxxx is replaced by student's last name
*/

{
public static void main(String[] args)
{
ArrayList<Integer> numbers = new ArrayList<Integer>();
Scanner in = new Scanner(System.in);
boolean more = true;
System.out.println("Enter sequence of integers, followed by Q: ");

while (in.hasNextInt())
{
}

int size = (int) Math.ceil(Math.sqrt(numbers.size()));
int k = 0;
for (int i = 0; i < size ; i++)
{
for (int j = 0; j < size ; j++)
{
if (k < numbers.size())
{
System.out.printf("%4d", numbers.get(k));
k++;
}
}
System.out.println();
}
if (size * size == numbers.size())
{
Squares mySquare = new Squares(numbers);

System.out.println("\n******** Square " + count + " ********");

//print the square
mySquare.printSquare();

if(mySquare.isMagic())
{
System.out.println("It's a magic square.");
}
else
System.out.println("It's not a magic square.");
}
else
System.out.println("It's not a square.");
}
}

```

#5 macosxnerd101

• Games, Graphs, and Auctions

Reputation: 12186
• Posts: 45,250
• Joined: 27-December 08

Re: 2D ArrayList User Input Determines Size and Output

Posted 14 April 2010 - 08:33 AM

I believe Dogstopper explained your first error well. As for your second error, you do not declare the variable count, so it does not exist. Therefore, when you go to print it, you are getting errors.

Reputation: 2
• Posts: 20
• Joined: 05-April 10

Re: 2D ArrayList User Input Determines Size and Output

Posted 14 April 2010 - 12:12 PM

Thanks for your help dogstopper and macosxnerd101.

Any help with the design of the constructor, even just pointing me in the right direction on how to build something that takes the input here would be great. I fixed the counter problem but am still having trouble with the constructor. I see where it is building off of size. How do I get it to build off of the user input?

#7 macosxnerd101

• Games, Graphs, and Auctions

Reputation: 12186
• Posts: 45,250
• Joined: 27-December 08

Re: 2D ArrayList User Input Determines Size and Output

Posted 14 April 2010 - 12:41 PM

Your Squares class should not handle user input, if that is what you are asking. Instead, you could overload the constructor to accept a 2D array or another variable corresponding to one of your instance variables. The variable you pass to the constructor would be generated via user input in your main() method.

#8 Dogstopper

Reputation: 2965
• Posts: 11,222
• Joined: 15-July 08

Re: 2D ArrayList User Input Determines Size and Output

Posted 14 April 2010 - 01:37 PM

Sure! As macosxnerd101 said, it will be better to get user input for an array in the main and pass that array to the constructor...

In your case, i suggest copying the elements, just so you don;t have to worry about the way Java handles arrays (specifically Object arrays).
```public class Squares
{
int[][] table;
int[][] square;
int column, sumC;
int row, sumR;
int size;
int sumDiag, sumReverse;

//create new square of g

public Squares(int[][] array)
{
square = new int[array.length][array[0].length];
for (int x = 0; x < array.length; x++) {
for (int y = 0; y < array[0].length; y++) {
square[x][y] = array[x][y];
}
}

```

Reputation: 2
• Posts: 20
• Joined: 05-April 10

Re: 2D ArrayList User Input Determines Size and Output

Posted 14 April 2010 - 01:39 PM

"Instead, you could overload the constructor to accept a 2D array or another variable corresponding to one of your instance variables. The variable you pass to the constructor would be generated via user input in your main() method. "

What does that look like? That's what I don't understand is how to do. I get that I can't take input in Squares but how do I construct the overload?

Thanks

Reputation: 2
• Posts: 20
• Joined: 05-April 10

Re: 2D ArrayList User Input Determines Size and Output

Posted 14 April 2010 - 02:31 PM

Thanks so much Dogstopper ! I have it compiling and running now but I have a different error coming up. What do I do with this?

Enter sequence of integers, followed by Q:
16 3 2 13 5 10 11 8 9 6 7 12 4 15 14 1 Q
16 3 2 13
5 10 11 8
9 6 7 12
4 15 14 1
at Squares.<init>(Squares.java:22)
at Squares.main(Squares.java:117)

here are the lines in question:

```   square = new int[array.length][array[0].length];

```

```   Squares mySquare = new Squares(square);

```

#11 macosxnerd101

• Games, Graphs, and Auctions

Reputation: 12186
• Posts: 45,250
• Joined: 27-December 08

Re: 2D ArrayList User Input Determines Size and Output

Posted 14 April 2010 - 02:39 PM

```class Item{
private int quantity;
private double price;
private String name;

public Item(int quantity){
this.quantity = quantity;
}

public Item(double price){
this.price = price;
}

public Item(String name, int quantity, double price){
this.name = name;
this.quantity = quantity;
this.price = price;
}
}

```

Notice how I use multiple constructors for Item. Since each constructor has the same name, but different param lists, they are overloads. Basically, just define a method with the same name as an existing method, but different a param list.

As for your NullPointerException, can you post all of your code? Those two lines aren't enough to help us.

http://java.sun.com/...OO/methods.html

#12 Dogstopper

Reputation: 2965
• Posts: 11,222
• Joined: 15-July 08

Re: 2D ArrayList User Input Determines Size and Output

Posted 14 April 2010 - 02:41 PM

Can you show us that code in context? Both of those lines are legal...However, I suspect that the array parameter is null and so has no length. You shouldn't be using the square object and sending it back to itself unless that is main method sent:

```public static void main(String[] args) {
int[][] squareArr = new int[4][4];
Scanner scan = new Scanner(System.in);

for (int i = 0; i < squareArr.length; i++)
for (int j = 0; j < squareArr.length; j++)
squareArr[i][j] = scanner.next();

Squares s = new Squares(squareArr);
}

```

Reputation: 2
• Posts: 20
• Joined: 05-April 10

Re: 2D ArrayList User Input Determines Size and Output

Posted 14 April 2010 - 07:06 PM

Thanks macosxnerd101 for the explanation. That makes perfect sense. Here is the code after my latest fixes. I checked the array parameters in the Squares constructor but I still don't have a fix. I am sure it is simple but I am not seeing the forest for the trees.

```import java.util.ArrayList;
import java.util.Scanner;

/**
This class tests whether a sequence of inputs forms a magic square.
Xxxx is replaced by student's last name
*/

public class Squares
{
int[][] table;
static int[][] square;
int column, sumC;
int row, sumR;
int size;
int sumDiag, sumReverse;

//create new square
public Squares(int[][] array)
{
square = new int[array.length][array[0].length];
for (int x = 0; x < array.length; x++)
{
for (int y = 0; y < array[0].length; y++)
{
square[x][y] = array[x][y];
}
}
}

//return the sum of the values in the given row

public int sumRow(int row)
{
int sumRow = 0;
for(column = 0; column < square.length; column++)
{
sumR = sumR + table[row][column];
}
return sumR;
}

//return the sum of the values in the given column
public int sumCol(int col)
{
int sumC = 0;
for(row = 0; row < size; row++)
{
sumC = sumC + table[row][column];
}
return sumC;
}
//return the sum of the values in the main diagonal
public int sumMainDiag()
{
int sumDiag = 0;for (row = 0, column = square.length - 1; row < square.length; row++)
{
sumDiag += square[row][column];
column --;
}
return sumDiag;
}
//return the sum of the values in the other ("reverse") diagonal
public int sumOtherDiag()
{
int sumReverse = 0;
for (row = square.length-1, column = 0; column < square.length; row--)
{
sumReverse += square[row][column];
column++;
}
return sumReverse;
}
//return true if the square is magic (all rows, cols, and diags have same sum), false otherwise

public boolean isMagic()
{
boolean result = false;
if (sumR == sumC)
if (sumC == sumDiag)
if (sumDiag == sumReverse)
result = true;
return result;
}

public static void main(String[] args)
{
ArrayList<Integer> numbers = new ArrayList<Integer>();
Scanner in = new Scanner(System.in);
boolean more = true;
System.out.println("Enter sequence of integers, followed by Q: ");

while (in.hasNextInt())
{
}

int size = (int) Math.ceil(Math.sqrt(numbers.size()));
int k = 0;
for (int i = 0; i < size ; i++)
{
for (int j = 0; j < size ; j++)
{
if (k < numbers.size())
{
System.out.printf("%4d", numbers.get(k));
k++;
}
}
System.out.println();
}

if (size * size == numbers.size())
{
Squares mySquare = new Squares(square);

System.out.println("\n******** Square " + k + " ********");

if(mySquare.isMagic())
{
System.out.println("It's a magic square.");
}
else
System.out.println("It's not a magic square.");
}
else
System.out.println("It's not a square.");
}
}

```

My hat is off to you both for the help. I have just gotten into Java and DIC. I am hooked. Today I discovered the blogs thanks to Dogstopper. I have learned more in a lot here in just a week or so since joining DIC.

#14 Dogstopper

Reputation: 2965
• Posts: 11,222
• Joined: 15-July 08

Re: 2D ArrayList User Input Determines Size and Output

Posted 14 April 2010 - 07:51 PM

EDIT: AW CRAP! I forgot it was 2D arrays.

Don't really see what you're doing here:
```int size = (int) Math.ceil(Math.sqrt(numbers.size()));
int k = 0;
for (int i = 0; i < size ; i++)
{
for (int j = 0; j < size ; j++)
{
if (k < numbers.size())
{
System.out.printf("%4d", numbers.get(k));
k++;
}
}
System.out.println();
}

```

You code is throwing an error because numbers doesn't have a value. This is how you would convert an Integer arraylist to an int array:
```    		Integer[] squaresObject = (Integer[]) numbers.toArray();
int[] squares = new int[squaresObject.length];
for (int i = 0; i < squares.length; i++)
squares[i] = squaresObject[i];

```

This post has been edited by Dogstopper: 14 April 2010 - 07:58 PM