I'm doing a magicsquare program that allows a user to input numbers >0 to form a magicsquare. What a magic square is, is pretty much a square, meaning that n has to have n(squared) numbers. Much like ticTacToe, all the rows, columns, and diagonals each have the same sum to be considered a magic square When I run my program, It always confuses the 2D array set and claim that the set of numbers are a magicsquare when usually, it isnt necessarily so. Please help!
import java.util.Scanner;
public class SquareRunner
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
Square test = new Square();
System.out.println("Enter a row of integers. When you are finished, type 'n' in a new line");
boolean flag = false;
while(!flag)
{
String numbers = in.next();
if(numbers.equals("n"))
flag = true;
else
test.add(numbers);
}
test.isMagic();
}
}
public class Square
{
private int[][] values;
private int row;
public Square()
{
row = 0;
}
public void add(String numbers)
{
int b = 1;
int amount = numbers.length();
values = new int[amount][amount];
for(int j =0;j<amount;j++)
{
String a = numbers.substring(j,b);
int convert = Integer.parseInt(a);
values[row][j] = convert;
b++;
}
row++;
}
public Boolean isMagic()
{
int checkAmountColumns = values[0].length;
int checkAmountRows = values.length;
int isSquare = checkAmountColumns * checkAmountRows;
for(int q = 0;q<values.length;q++)
{
for(int w=0;w<values[0].length;w++)
{
int checkZero = values[q][w];
if(checkZero == 0)
{
System.out.print("To be a perfect square, your number of rows and columns, n must be a perfect ");
System.out.println("Square i.e. 9 total numbers is 3 numbers per row");
return false;
}
}
}
if(checkAmountColumns != checkAmountRows || Math.sqrt(isSquare) != checkAmountColumns)
{
System.out.print("To be a perfect square, your number of rows and columns, n must be a perfect ");
System.out.println("Square i.e. 9 total numbers is 3 numbers per row");
return false;
}
else
{
int magicNumber = 0;
int counter = 0;
int compareTo = 0;
//row to row
for(int i =0;i<values.length;i++)
{
for(int j = 0;j<values[0].length;j++)
{
values[i][j] += compareTo;
if(counter == 0)
values[i][j] += magicNumber;
}
counter ++;
compareTo = 0;
if(compareTo != magicNumber)
{
System.out.println("This Selection of numbers is not a perfect square");
return false;
}
}
//column to column
for(int i =0;i<values[0].length;i++)
{
for(int j = 0;j<values.length;j++)
{
values[j][i] += compareTo;
if(counter == 0)
values[j][i] += magicNumber;
}
counter ++;
compareTo = 0;
if(compareTo != magicNumber)
{
System.out.println("This Selection of numbers is not a perfect square");
return false;
}
}
System.out.println("This selection of numbers is a MagicSquare!");
return true;
}
}
}
The first thing I notice is that your add() method probably won't work correctly. Every time you call it, you overwrite the previous values member with a newly allocated array. This throws away the previous row that you entered.
Same answer as Greg.
Add this to your add method and delete the initialisation of your values array.
if(values == null){values = new int[amount][amount];}
Related
In the code below i try to read a file with the size of a 2d array and the numbers for each cell. Then the program must find a number that can be added in the cell with a zero value in magic array. All this in order to create magic squares based on the initialized magic array with the elements of the external file. The problem is that i always get the message "magic squares cannot be created" even when the if statement in next_successor method get true from all the arguments? where is the problem? i got really stuck any help will be appreciated!
so i think the main problem is with the methods:
next_successor
check_row
check_column
check_diagonals
The rules that i have to follow in order to create the methods are:
In order for current_number to be inserted into magic[row,column], the following checks (by check_row(), check_column() and check_diagonals()) should be made:
For each of the row, column, and possibly main diagonals (in the case of row=column or row=N-column-1) to which position magic[row,column] belongs, and for each current_number that does not has yet been inserted into the magic square (according to the value used[current_number-1]), we perform the following checks to decide whether current_number can be inserted into magic[row,column]:
Suppose (in the row or column or main diagonal where the position magic[row,column]) is located after the number current_number is placed in the position magic[row,column], m positions have been filled, so there are N-m empty positions left to be filled.
Let 𝑠 be the sum of the numbers already in the row or column or main diagonal (including current_number).
Let 𝑎 be the sum of the 𝑁−𝑚 smallest numbers (from 1 to N*N) not yet entered into the magic square (according to the table used) and 𝑏 the sum of the 𝑁−𝑚 largest numbers not yet entered (similarly) . If 𝑚=𝑁 then 𝑎=𝑏=0.
Let 𝐶 be the magic constant. If 𝑠+𝑎>𝐶 or 𝑠+𝑏<𝐶, for some row or column or main diagonal to which magic[row, column] belongs, then current_number cannot be inserted into position magic[row,column ], i.e. the respective check_row(), check_column() and check_diagonals() will return false, otherwise they will all return true.
the txt external file has the following elements:
6
0 0 13 0 20 0
0 15 0 0 0 12
8 0 2 0 31 0
0 14 0 7 0 1
28 0 0 0 0 0
0 0 6 0 0 21
import java.io.*;
import java.util.*;
public class MainSolver{
static ArrayList<MagicSquare> stuckAL;
static Stack<MagicSquare> stuckST;
static LinkedList<MagicSquare> stuckLL;
static int datastructure;
static int N = 0;
static int[][] input;
public static void main() throws IOException {
//THE PROGRAM READS THE EXTERNAL FILE
Scanner sc = new Scanner(System.in);
System.out.print("Enter the file name: ");
String fileName = sc.next();
System.out.println("Enter data structure to use: (arraylist, stack, queue, linkedlist): ");
System.out.println("1: arraylist");
System.out.println("2: stack");
System.out.println("3: queue");
System.out.println("4: linkedlist");
datastructure = sc.nextInt();
File file = new File(fileName);
Scanner fileScanner = new Scanner(file);
N = fileScanner.nextInt();
input = new int[N][N];
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
input[i][j] = fileScanner.nextInt();
}
}
MagicSquare.size = N;
MagicSquare ms = new MagicSquare();
for(int i=0; i<N ;i++){
for(int j=0; j<N ;j++){
ms.set_cell(i,j,input[i][j]);
if (ms.magic[i][j] != 0) {
ms.used[ms.magic[i][j]-1] = true;
}
}
}
ms.check_used();
//PRINTING THE INPUT AND MAGIC ARRAY
System.out.println("Size of array from file: "+N);
ms.display(input);
System.out.println();
System.out.println("Size of array from MagicSquare object: "+ms.N);
ms.display(ms.magic);
fileScanner.close();
//IT STARTS THE INITIALIZATION OF DATASTRUCTURES & START THE SEARCH OF SUCCESSORS
initialize_search(ms,datastructure);
search(datastructure);
}
//THIS PART OF CODE NEEDS TO STAY AS IT IS. CAN'T MAKE CHANGES
static void initialize_search(MagicSquare ms, int datastructure) {
switch (datastructure) {
case 1:
case 2:
stuckAL = new ArrayList();
stuckAL.add(ms);
break;
case 3:
stuckST=new Stack();
stuckST.push(ms);
break;
case 4:
stuckLL=new LinkedList();
stuckLL.add(ms);
break;
default:
break;
}
}
//THIS PART OF CODE NEEDS TO STAY AS IT IS. CAN'T MAKE CHANGES
static void search(int datastructure) {
MagicSquare current = null, next;
switch (datastructure) {
case 1:
System.out.println("Search using ArrayList as a Stack");
break;
case 2:
System.out.println("Search using ArrayList as a Queue");
break;
case 3:
System.out.println("Search using Stack as a Stack");
break;
case 4:
System.out.println("Search using LinkedList as a Queue");
break;
default:
break;
}
boolean empty_frontier=false;
while (!empty_frontier) {
if (datastructure == 1) {
current = stuckAL.get(stuckAL.size()-1);
stuckAL.remove(stuckAL.size()-1);
}
else if (datastructure == 2) {
current = stuckAL.get(0);
stuckAL.remove(0);
}
else if (datastructure == 3)
current = stuckST.pop();
else if (datastructure == 4)
current = stuckLL.removeFirst();
current.initialize_successors();
while((next=current.next_successor()) != null)
{
if (next.numbers == N*N)
{
System.out.println("SOLUTION FOUND ");
System.out.println("==============");
next.display(next.magic);
return;
}
else switch (datastructure) {
case 1: ;
case 2: stuckAL.add(next);
break;
case 3: stuckST.push(next);
break;
case 4: stuckLL.addLast(next);
break;
}
}
switch (datastructure) {
case 1:
if (stuckAL.isEmpty())
empty_frontier=true;
break;
case 2:
if (stuckAL.isEmpty())
empty_frontier=true;
break;
case 3:
if (stuckST.isEmpty())
empty_frontier=true;
break;
case 4:
if (stuckLL.isEmpty())
empty_frontier=true;
break;
}
}
System.out.println("MAGIC SQUARES CANNOT BE CREATED");
}
}
class MagicSquare {
public static int size;
public int N;
public int C;
public int[][] magic;
public boolean[] used;
public int numbers;
public int row;
public int column;
public int current_number;
//THIS CONSTRUCTOR WITHOUT ARGUMENTS INITIALIZE N and C, the magic array and the numbers variable with zeros, as well as the used array with false values.
public MagicSquare() {
this.N = size;
C = N*((N*N+1)/2);
magic = new int[N][N];
used = new boolean[N*N];
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
magic[i][j] = 0;
}
}
for (int i = 0; i < used.length; i++) {
used[i] = false;
}
numbers = 0;
row = 0;
column = 0;
current_number = 0;
}
//THIS CONSTRUCTOR creates a copy of the object (mainly regarding the N, C, magic, numbers and used variables)
public MagicSquare(MagicSquare ms) {
N = ms.N;
C = ms.C;
magic = new int[N][N];
used = new boolean[N*N];
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
magic[i][j] = ms.magic[i][j];
}
}
for (int i = 0; i < used.length; i++) {
used[i] = ms.used[i];
}
numbers = ms.numbers;
row = ms.row;
column = ms.column;
current_number = ms.current_number;
}
//METHOD THAT IS CALLED TO FILL EACH CELL OF MAGIC ARRAY WITH NUMBER FROM EXTERNAL FILE
public void set_cell(int row, int col, int number){
if (number>=1 && number<=N*N && row>=0 && row<N*N && col>=0 && col<N*N && magic[row][col]==0){
magic[row][col] = number;
numbers++;
}
}
//METHOD THAT: "initializes" the process of constructing the "successors" of a MagicSquare object. As a successor we characterize a new object, which is in principle the same as its "parent" (with regard to the fields magic, numbers and used), but has an additional position of the magic square filled in in a valid way. The initialize_successors() method will practically give as values to the row and column fields the row and column of the next null of the magic table, while in addition it will initialize the value of the current_number field (eg, to 0).
public void initialize_successors() {
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if (magic[i][j] == 0) {
row = i;
column = j;
current_number = 0;
return;
}
}
}
}
//METHOD THAT: each time it is called it will find the next value of current_number that can be placed in magic[row,column], construct an object that is a copy of the current object, but with the current_number in magic[row,column], and will return it. If no next value of current_number is found that can be inserted into magic[row, column], it will return null. In order for the current value of current_number to be inserted in the magic[row, column] position, this value must not already be used in the magic square (checked via the used table), and the methods check_row(), check_column() and check_diagonals() to return true.
public MagicSquare next_successor() {
MagicSquare successor;
while (current_number < N*N) {
current_number++;
if (!used[current_number-1] && check_row() && check_column() && check_diagonals()) {
successor = new MagicSquare(this);
successor.magic[row][column] = current_number;
successor.used[current_number-1] = true;
successor.numbers++;
/*if(column == N-1) {
successor.row++;
successor.column = 0;
}
else {
successor.column++;
}*/
System.out.println("next successor returns successor!");
return successor;
}
//break;
}
System.out.println("next successor returns null!");
return null;
}
//METHOD THAT: returns true if current_number is consistent with the row numbers of magic[row,column], otherwise returns false.
public boolean check_row(){
int sum = current_number;
int m = numbers;
int emptyPositions = N - m;
int a = getSumOfSmallestElementsNotUsed();
int b = getSumOfLargestElementsNotUsed();
System.out.println();
System.out.println("current number being tested in row: "+current_number);
for (int i = 0; i < N; i++) {
if (magic[row][i] != 0) {
sum += magic[row][i];
}
}
System.out.println("sum of numbers in row: "+sum);
if (sum + a > C || sum + b < C) {
System.out.println("row gives false!");
return false;
}
System.out.println("row gives true!");
return true;
}
//METHOD THAT: returns true if current_number is consistent with the column numbers of magic[row,column], otherwise returns false.
public boolean check_column(){
int sum = current_number;
int m = numbers;
int emptyPositions = N - m;
int a = getSumOfSmallestElementsNotUsed();
int b = getSumOfLargestElementsNotUsed();
System.out.println("current number being tested in column: "+current_number);
for (int i = 0; i < N; i++) {
if (magic[i][column] != 0) {
sum += magic[i][column];
}
}
System.out.println("sum of numbers in column: "+sum);
if (sum + a > C || sum + b < C) {
System.out.println("column gives false!");
return false;
}
System.out.println("column gives true!");
return true;
}
//METHOD THAT: which will return true if current_number is consistent with the numbers of each of the two main diagonals of the magic square, provided that magic[row,column] belongs to one or the other or both of the main diagonals of the magic square respectively, otherwise it will return false.
public boolean check_diagonals(){
int sum = current_number;
int m = numbers;
int emptyPositions = N - m;
int a = getSumOfSmallestElementsNotUsed();
int b = getSumOfLargestElementsNotUsed();
System.out.println("current number being tested in diagonals: "+current_number);
if (row == column) { //main diagonal
for (int i = 0; i < N; i++) {
if (magic[i][i] != 0) {
sum += magic[i][i];
}
}
} else if (row == N-column-1) { //other diagonal
for (int i = 0; i < N; i++) {
if (magic[i][N-i-1] != 0) {
sum += magic[i][N-i-1];
}
}
}
System.out.println("sum of numbers in diagonal: "+sum);
if (sum + a > C || sum + b < C) {
System.out.println("diagonals gives false!");
return false;
}
System.out.println("diagonals gives true!");
return true;
}
//METHOD THAT: calculate the sum of the 2 first empty elements of used array and therefore the smallest
public int getSumOfSmallestElementsNotUsed(){
int sum = 0;
int count = 0;
for (int i = 0; i < used.length; i++) {
if (!used[i]) {
sum += (i + 1);
count++;
}
if (count == 2) {
break;
}
}
System.out.println("sum of 2 smallest elements: "+sum);
return sum;
}
//METHOD THAT: calculate the sum of the 2 last empty elements of used array and therefore the largest
public int getSumOfLargestElementsNotUsed(){
int sum = 0;
int count = 0;
for (int i = used.length - 1; i >= 0; i--) {
if (!used[i]) {
sum += (i + 1);
count++;
}
if (count == 2) {
break;
}
}
System.out.println("sum of 2 largest elements: "+sum);
return sum;
}
public boolean isComplete() {
return numbers == N*N;
}
public void display(int array[][]) {
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
System.out.print(array[i][j] + " ");
}
System.out.println();
}
System.out.println();
}
public void check_used(){
int i,j;
int k=0;
for(i=0; i<magic.length; i++){
for(j=0; j<magic[i].length; j++){
System.out.println("POSITION IN USED ARRAY: "+k+" WITH VALUE: "+used[k]+" FROM POSITION IN MAGIC ARRAY: "+i+","+j+" WITH VALUE: "+magic[i][j]);
k++;
}
}
}
}
What do you think this computes?
this.N = size;
C = N*((N*N+1)/2); // C = 108
The size is 6 for your problem.
So you will need the values 1 thru 36 inclusive.
let max = N*N. So the sum of 1 thru 36 is max*(max+1)/2.
divide by N to get the col or row sum and you ((max*(max+1))/2)/N = 111.
or (N*(max+1))/2)
in your case is should have been (N*(N*N+1))/2.
The issue was that. (N*N+1) is 37. Then you divide by 2 which drops the fraction (int arithemetic). You need to first multiply by N and then divide by 2.
I'm trying to make a lottery game in java to run in the console afterwards with user input. I have a [3][9] array of random numbers between 1-9 in column 1, 10-19 in column 2, until 90, with half the numbers being 0, meaning they aren't part of the game or simply blanks.
So far, I have the numbers created in the array and they output fine, but I need to allow the user to have input and the numbers being guessed to start as blanks (or x instead of the number) and when the user actually gets the right number, it would switch that with the number generated previously. This would repeat itself until all the numbers were right, and then a message indicating a win would show.
How can I compare the inputs with the values generated? And how do I hide these values until they are guessed by the user?
Final Edit: If a line is completed with correct numbers, how do I keep track of this to also display message if this happens?
This is the random array index:
import java.util.Arrays;
import java.util.Random;
class Loto {
public static void main(String[] args) {
int[][] cartao = new int[3][9];
Random rand = new Random();
for(int i = 0; i< cartao.length; i++){
for(int j = 0; j< 5; j++){
int x = rand.nextInt(89) + 1;
while(cartao[i][x / 10] !=0) {
x = rand.nextInt(89) + 1;
}
cartao[i][x / 10] = x;
}
}
for(int[] row : cartao){
System.out.println(Arrays.toString(row));
}
}
}
You have to store what has been guessed correctly or not. For example you can use an auxiliary boolean matrix though it is not necessary (u can use only your card array, storing correctly guessed guesses has -1 for example), but it is easier to the eye I would say
public class Lotto {
boolean correctlyGuessed[][];
int lottoCard[][];
public Lotto() {
correctlyGuessed = new boolean[3][9];
lottoCard = new int[3][9];
Random rand = new Random();
for(int i = 0; i< lottoCard.length; i++){
for(int j = 0; j< 5; j++){
int x = rand.nextInt(89) + 1;
while(lottoCard[i][x / 10] !=0) {
x = rand.nextInt(89) + 1;
}
lottoCard[i][x / 10] = x;
}
}
}
public boolean guess(int row, int col, int number) {
if(lottoCard[row][col] == number) {
correctlyGuessed[row][col] = true;
return true;
}
return false;
}
public boolean hasLottoEnded() {
for(boolean[] arr:correctlyGuessed) {
for(boolean guess: arr) {
if(!guess) //if a guess is still false the game hasn't ended
return false;
}
}
return true;
}
public int getNumber(int row, int col) {
return lottoCard[row][col];
}
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
for(int row = 0; row < lottoCard.length; row++) {
for(int col = 0; col < lottoCard[row].length; col++) {
if(correctlyGuessed[row][col])
sb.append(lottoCard[row][col] + " ");
else
sb.append("X ");
}
//spacing
sb.append("\n");
}
return sb.toString();
}
public static void main(String[] args) {
Lotto card = new Lotto();
Scanner sc = new Scanner(System.in);
while(!card.hasLottoEnded()) { //loop whilst the game hasn't ended
System.out.println("Row:");
int row = sc.nextInt();
System.out.println("Column:");
int col = sc.nextInt();
System.out.println("Number:");
int number = sc.nextInt();
if(card.guess(row, col, number))
System.out.println("You have guessed correctly!");
else
System.out.println("Wrong guess :(");
System.out.println(card);
}
System.out.println("You win!");
sc.close();
}
}
So far i can generate random 20 number that i want...but when i want to Search for my random 20 number ...it alwayS Show "the number you enter cannot found " why ???how do i Search the value from the number i generated ? would be happy if Someone can teach me how to do .
package labtask.pkg5;
import java.util.Scanner;
import java.util.Random;
public class Labtask5 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
int search = 1;
int[] array = new int[20];
Scanner read = new Scanner(System.in);
Random r = new Random(); //generate random number
for (int x = 0; x < 20; x++) {
System.out.println(r.nextInt(100));
}
while (search != 0) //Search for a number
{
System.out.println("Search a number");
search = read.nextInt();
if (SearchValue(search, array) == true) {
System.out.println("The number you enter been found");
} else {
System.out.println("The number you enter did not found");
}
}
}
public static boolean SearchValue(int search, int[] array) {
for (int y = 0; y < 20; y++) {
if (search == array[y]) {
return true;
} else {
return false;
}
}
return true;
}
}
Your first problem is with this function:
public static boolean SearchValue(int search, int[] array) {
for (int y = 0; y < 20; y++) {
if (search == array[y]) {
return true;
} else {
return false;
}
}
return true;
}
You will always return either true or false on the first iteration of the loop and you will never get past y = 0.
Additionally, you do not need to hardcode the value 20. The array is aware of its own size.
I would expect this to look like:
public static boolean SearchValue(int search, int[] array) {
for (int y = 0; y < array.length; y++) {
if (search == array[y]) {
return true;
}
}
return false;
}
1 things:
you are printing 20 random numbers only, but not assigning it into the array:
for (int x = 0; x<20; x++){
System.out.println(r.nextInt(100));
}
do instead:
for (int x = 0;x<20;x++) {
array[x] = r.nextInt(100);
System.out.println(array[x]);
}
on the other hand, the method:
SearchValue(int search, int[] array)
is returning some boolean immediantly after checking the 1st element in the array, you need to BROWSE the whole array instead...
do instead something like:
public static boolean SearchValue(int search, int[] array) {
for (int y = 0; y < 20; y++) {
if (search == array[y]) {
return true;
}
}
return false;
}
Hello guys, i'm having trouble with creating a sequential
search algorithm for a two dimensional int array. not sure exactly how to go about augmenting the while loop so it works , the example i'm using does it exactly how i wrote it out, as you can see my compiler is complaining about the incompatibility with the way its written out!
import java.util.*;
import javax.swing.*;
public class pencilneck
{
public static void main(String []alex)
{
int ROWS = 6;
int COLS = 3;
int[][] chargeAcc = new int[ROWS][COLS];
Scanner keyboard = new Scanner(System.in);
for(int row = 0; row < ROWS; row++)
{
for(int col = 0; col < COLS; col++)
{
System.out.print("Enter Account");
chargeAcc[row][col] = keyboard.nextInt();
}
}
System.out.print("Enter an account to be Charged");
int input = keyboard.nextInt();
int results = SequentialSearch(chargeAcc,input);
if(results ==-1)
{
System.out.println("that is an invalid #");
}
else
{
System.out.println("the # is valid");
}
}
public static int SequentialSearch(int[][] array, int value)
{
int index1 = 0;
int element = -1;
boolean found = false;
while(!found && index1 == value)
{
if(array[index] == value)
{
found = true;
element = index;
}
index++;
}
return element;
}
}
Your question doesn't quite make sense, but the bug in your code is easy enough to find.
while(!found && index1 == value)
This says in plain english, do the stuff in the loop while these conditions are both true:
Found is false
index (index of array) is equal to value (number you want to find in array)
At the start of the loop, index == 0. Since value is likely nonzero, the second condition is false and the loop never runs, causing SequentialSearch to return -1 immediately.
Now that you know what the problem is, I'll leave it to you to take time to understand what you did wrong and figure out how to fix it.
Array[index] is not an int, is an array.
i think what you are looking for is something like this:
enter code here
import java.util.*;
import javax.swing.*;
public class pencilneck
{
public static void main(String []alex)
{
int ROWS = 6;
int COLS = 3;
int[][] chargeAcc = new int[ROWS][COLS];
Scanner keyboard = new Scanner(System.in);
for(int row = 0; row < ROWS; row++)
{
for(int col = 0; col < COLS; col++)
{
System.out.print("Enter Account");
chargeAcc[row][col] = keyboard.nextInt();
}
}
System.out.print("Enter an account to be Charged");
int input = keyboard.nextInt();
int results = SequentialSearch(chargeAcc,input);
if(results ==-1)
{
System.out.println("that is an invalid #");
}
else
{
System.out.println("the # is valid");
}
}
public static int SequentialSearch(int[][] array, int value)
{
int rowIndex = 0;
int element = -1;
boolean found = false;
while(!found && index1 != value)
{
for(int i =0;i<array[index].length;i++)
{
if(array[index][i] == value)
{
found = true;
element = index;
}
}
index++;
}
return element;
}
for each row you search in all of it's cols.
(you could break the for loop if found, to gain efficiency.
Trying to write a program that "rolls" dice and displays the results of the players and computer's rolls, as well as find how many of each number was rolled. Say, player rolls 3 4 3 5 6, then the player has a match composed of 2 3's. Haven't wrote the code to display the matching yet.
My problem is that I am trying to record the rolls to an ArrayList, then compare each number for the players and computers rolls from the ArrayList, and count up the number of each number's occurrence, but it I keep getting the error of
error: incomparable types: DieClass and int
Whenever I try to compare from the ArrayList
The program in question uses methods from the class DieClass
import java.util.ArrayList;
public class DieTester
{
private static ArrayList<DieClass> player = new ArrayList<DieClass>();
private static ArrayList<DieClass> computer = new ArrayList<DieClass>();
public static void main(String[] args)
{
for(int a = 1; a <= 5; a++)
{
DieClass roller = new DieClass();
player.add(roller);
}
for(int a = 1; a <= 5; a++)
{
DieClass roller = new DieClass();
computer.add(roller);
}
System.out.println("The user rolls: "+player);
System.out.println("The computer rolls: "+computer);
}
public String findMatching()
{
int count1 = 0;
int count2 = 0;
int count3 = 0;
int count4 = 0;
int count5 = 0;
for(int i=1; i<player.size(); i++)
{
if(player.get(i)==1)
{
count1++;
}
else if(player.get(i)==2)
{
count2++;
}
else if(player.get(i)==3)
{
count3++;
}
else if(player.get(i)==4)
{
count4++;
}
else if(player.get(i)==5)
{
count5++;
}
}
for(int i=1; i<player.size(); i++)
{
if(computer.get(i)==1)
{
count1++;
}
else if(computer.get(i)==2)
{
count2++;
}
else if(computer.get(i)==3)
{
count3++;
}
else if(computer.get(i)==4)
{
count4++;
}
else if(computer.get(i)==5)
{
count5++;
}
}
}
}
Your problem is that you are comparing DieClass with Integers
if(player.get(i)==1)
For the counters, why don't you use an array of int? like
int counters [] = new int[6];
counters[2]++;
Please post DieClass, however, I think that your code should be like this.
for (DieClass dieClass : player) {
counters[dieClass.getNumber()-1]++; //Supose that DieClass has a getNumber method and set minus one because counters goes from 0 to 5
}