For this intro-level assignment, I have to set up a 2D multidimensional array from a file and from a double[][] a and apply several methods to them. For now, I'm mostly concerned with simply initializing the arrays. I'm trying to figure out a way to take a test file, read the first int as the number of rows, the first integer of each line as the number of columns per row, and each double as a member of the array.
public class MDArray
{
static int rowCount;
static int columnCount;
private static double[][] mdarray = new double[rowCount][columnCount];
public MDArray(double[][] a)
{
mdarray = a;
}
public MDArray(String file)
{
Scanner input = null;
try
{
input = new Scanner(new FileInputStream("ragged.txt"));
}
catch (FileNotFoundException e)
{
System.out.println("File Not Found.");
System.exit(0);
}
while(input.hasNextDouble())
{
rowCount = input.nextInt();
for(int i = 0; i < rowCount; i++)
{
columnCount = input.nextInt();
for(int j = 0; j < columnCount; j++)
{
double value = input.nextDouble();
mdarray[i][j] = value;
}
}
}
}
public static boolean isRagged()
{
for(int i = 0; i < mdarray.length; i++)
{
int rowLength1 = mdarray.length;
for(int j = i + 1; j < mdarray.length; j++)
{
int rowLength2 = mdarray.length;
if(rowLength1 != rowLength2)
{
return true;
}
}
}
return false;
}
public static int getNumberOfRows()
{
int numRows = 0;
for(int i = 0; i < mdarray.length; i++)
{
numRows++;
}
return numRows;
}
public static int getNumberOfCols()
{
int numCols = 0;
for(int i = 0, j = i + 1; i < mdarray.length; i++)
{
for(int k = 0; k < mdarray[i].length; k++)
{
if(mdarray[i].length > mdarray[j].length)
{
numCols++;
}
}
}
return numCols;
}
public static double getValAt(int i, int j)
{
if(i > mdarray.length || j > mdarray[i].length)
{
double invalid = Double.NaN;
return invalid;
}
double valAt = mdarray[i][j];
return valAt;
}
public static void sort(boolean byColumn)
{
if(isRagged() == true)
{
System.out.println("Ragged arrays cannot be sorted by column.");
}
else{
for(int i = 0; i < mdarray.length; i++)
{
for(int j = 0; j < mdarray[i].length; j++)
{
for(int k = j + 1; k < mdarray[i].length; k++)
{
if(mdarray[i][j] < mdarray[i][k])
{
double temp = mdarray[i][j];
mdarray[i][k] = mdarray[i][j];
mdarray[i][j] = temp;
}
}
}
}
}
}
public static int hamming(boolean byColumn)
{
int hamVal = 0;
if(isRagged() == true)
{
System.out.println("Ragged arrays cannot be sorted by column.");
}
else{
for(int i = 0; i < mdarray.length; i++)
{
for(int j = 0; j < mdarray[i].length; j++)
{
for(int k = j + 1; k < mdarray[i].length; k++)
{
if(mdarray[i][j] < mdarray[i][k])
{
double temp = mdarray[i][j];
mdarray[i][k] = mdarray[i][j];
mdarray[i][j] = temp;
hamVal++;
}
}
}
}
}
return hamVal;
}
public static double[] max()
{
double[] maxVal = new double[mdarray.length];
for(int i = 0, j = i + 1; i < maxVal.length; i++)
{
for(int k = 0; k < mdarray[i].length; k++)
{
if(mdarray[i][k] > mdarray[j][k])
{
maxVal = mdarray[i];
}
}
}
return maxVal;
}
public String toString()
{
String arrayString = "";
for(int i = 0; i < mdarray.length; i++)
{
for(int j = 0; j < mdarray[i].length; j++)
{
arrayString += ", " + mdarray[i][j];
}
arrayString = arrayString + "/n";
}
return arrayString;
}
}
This was the file I was testing the MDArray(String file) with:
3
2 4.1 8.9
5 9.5 2.0 7.3 2.1 8.9
3 1.3 5.2 3.4
I think the problem is that the rowCount and columnCount integers are not initialized, but I'm not sure how to initialize them to a variable length with basic array skills. This is also affecting the other constructor as well. Being an intro-level course, I am not supposed to use more advanced techniques such as ArrayList. In addition, I can't verify if the methods are correct, since I don't have an array to test them with.
EDIT: While I did implement many of the suggestions in the answers, such as changing everything to non-static and other changes, I'm still getting a NullPointerException for the line mdarray[i][j] = input.nextDouble();. I assume it has to do with the private double[][] mdarray, which is required in the assignment specifications. Now I'm trying to find a way to initialize it such that it can be overridden in the later methods.
You have to initialize the array in your constructor, since that's when you know the dimensions :
public MDArray(String file)
{
Scanner input = null;
try {
input = new Scanner(new FileInputStream("ragged.txt"));
}
catch (FileNotFoundException e) {
System.out.println("File Not Found.");
System.exit(0);
}
rowCount = input.nextInt();
mdarray = new double[rowCount][]; // init the array
for(int i = 0; i < rowCount; i++) {
columnCount = input.nextInt();
mdarray[i] = new double[columnCount]; // init the current row
for(int j = 0; j < columnCount; j++) {
mdarray[i][j] = input.nextDouble();
}
}
}
You could initialize your arrays by putting the amount of rows and columns on the first 2 lines of your multidimensional array, if i had 10 rows and 12 columns i could do something like this:
public void arrayStuff() {
File fileToRead = new File("YOUR LINK HERE");
String[][] data;
try (BufferedReader reader = new BufferedReader(new FileReader(fileToRead))) {
String line;
data = new String[Integer.parseInt(reader.readLine())][Integer.parseInt(reader.readLine())];
while((line = reader.readLine()) != null) {
// read the rest here..
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I am using an AutoCloseable (which is why the try is between these ()'s, but this is so that i don't have to close it afterwards.
Basically, first i read the amount of rows there are and then the amount of columns there are, so if i had this file:
10
12
a b c d e f g h i j
a b c d e f g h i j
a b c d e f g h i j
a b c d e f g h i j
a b c d e f g h i j
a b c d e f g h i j
a b c d e f g h i j
a b c d e f g h i j
a b c d e f g h i j
a b c d e f g h i j
a b c d e f g h i j
a b c d e f g h i j
It'd be able to read all of this, because the amount of rows and columns were defined in the file.
You don't use the fields rowCount and columnCount: you can remove them
The mdarray field should be non-static, so should be the methods that use them (if it was a utility class, you wouldn't have any constructor)
The arrays can be created while reading the file:
Scanner input = null;
try
{
input = new Scanner(new FileInputStream("ragged.txt"));
}
catch (FileNotFoundException e)
{
System.out.println("File Not Found.");
System.exit(0);
}
int rowCount = input.nextInt();
mdarray = new double[rowCount][];
for(int i = 0; i < rowCount; i++)
{
int columnCount = input.nextInt();
mdarray[i] = new double[columnCount];
for(int j = 0; j < columnCount; j++)
{
double value = input.nextDouble();
mdarray[i][j] = value;
}
}
methods getNumberOfRows() and getNumberOfCols() count be much simpler:
public int getNumberOfRows()
{
return mdarray.length;
}
public int getNumberOfCols() {
int result = 0;
for (double[] col: mdarray) {
if (col.length > result) {
result = col.length;
}
}
return result;
}
In getValueAt(), the test is wrong; it should be:
if(i >= mdarray.length || j >= mdarray[i].length)
Related
currently I am trying to implement a CPLEX exact solution for the Asymmetric Capacitated Vehicle Routing Problem with the MTZ sub-tour elimination constraints.
My problems occurs when I try to implement Lazy Constraint Callbacks. More specifically I get a null pointer exception. There are almost no tutorials for implementing callbacks, so your help will be deeply appreciated.
This is my code:
CVRP class
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import ilog.concert.*;
import ilog.cplex.*;
public class ACVRP {
// euclidean distance method
public static double distance(int x1, int y1, int x2, int y2) {
return Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));
}
public static void solveModel() {
int n = 32; // number of customers
int k = 5; // number of vehicles
int c = 100; // capacity of vehicles
int datacoords[][] = new int[n][2];
double[][] node = new double[n][n]; // dissimilarity matrix
int[] demand = new int[n]; // demand of every customer
try {
// load matrixes
FileReader frd = new FileReader("demands.txt");
FileReader frcoords = new FileReader("coords.txt");
BufferedReader brd = new BufferedReader(frd);
BufferedReader brcoords = new BufferedReader(frcoords);
String str;
int counter = 0;
while ((str = brd.readLine()) != null) {
String[] splitStr = str.trim().split("\\s+");
demand[counter] = Integer.parseInt(splitStr[1]);
counter++;
}
counter = 0;
while ((str = brcoords.readLine()) != null) {
String[] splitStr = str.trim().split("\\s+");
datacoords[counter][0] = Integer.parseInt(splitStr[1]);
datacoords[counter][1] = Integer.parseInt(splitStr[2]);
counter++;
}
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
node[i][j] = distance(datacoords[i][0],datacoords[i][1],datacoords[j][0],datacoords[j][1]);
// if (i == j ){
// node[i][j] = 99999999;
// }
}
}
brd.close();
brcoords.close();
IloCplex cplex = new IloCplex();
// variables
IloIntVar[][] x = new IloIntVar[n][];
for (int i = 0; i < n; i++) {
x[i] = cplex.boolVarArray(n);
for (int j = 0; j < n; j++) {
x[i][j].setName("x." + i + "." + j );
}
}
// mtz variables
IloNumVar[] u = cplex.numVarArray(n, 0, Double.MAX_VALUE);
for (int j = 0; j < n; j++) {
u[j].setName("u." + j);
}
//objective
IloLinearNumExpr conObj = cplex.linearNumExpr();
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if ( i != j ){
conObj.addTerm(node[i][j], x[i][j]) ;
}
}
}
cplex.addMinimize(conObj);
// constraints
for (int i = 1; i < n; i++) {
IloLinearNumExpr equation1 = cplex.linearNumExpr();
for (int j = 0; j < n; j++) {
if (i!=j) {
equation1.addTerm(1.0, x[i][j]);
}
}
cplex.addEq(equation1, 1.0);
}
for (int j = 1; j < n; j++) {
IloLinearNumExpr equation2 = cplex.linearNumExpr();
for (int i = 0; i < n; i++) {
if (i!=j) {
equation2.addTerm(1.0, x[i][j]);
}
}
cplex.addEq(equation2, 1.0);
}
IloLinearNumExpr equation3 = cplex.linearNumExpr();
for (int i = 1; i < n; i++) {
equation3.addTerm(1.0, x[i][0]);
}
cplex.addEq(equation3, k);
IloLinearNumExpr equation4 = cplex.linearNumExpr();
for (int j = 1; j < n; j++) {
equation4.addTerm(1.0, x[0][j]);
}
cplex.addEq(equation4, k);
cplex.use(new LazyContstraintMTZ(n, c, demand, x, u, cplex));
//parameters
//cplex.setParam(IloCplex.Param.TimeLimit,50);
//cplex.setParam(IloCplex.Param.Preprocessing.Reduce, 0);
// cplex.setParam(IloCplex.Param.RootAlgorithm, IloCplex.Algorithm.Primal);
// solve model
cplex.solve();
cplex.exportModel("model.lp");
System.out.println(cplex.getBestObjValue());
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i != j) {
if (cplex.getValue(x[i][j]) != 0) {
System.out.println("name: " + x[i][j].getName() + " value: " + cplex.getValue(x[i][j]));
}
}
}
}
// end
cplex.end();
} catch (IloException | NumberFormatException | IOException exc) {
exc.printStackTrace();
}
}
}
class for lazy constraint :
import ilog.concert.*;
import ilog.cplex.*;
public class LazyContstraintMTZ extends IloCplex.LazyConstraintCallback {
int n; // number of customers
int c; // capacity of vehicles
int[] demand; // demand of every customer
IloIntVar[][] x;
IloNumVar[] u;
IloCplex cplex;
IloRange[] rng;
//constructor
LazyContstraintMTZ(int n, int c, int[] demand, IloIntVar[][] x, IloNumVar[] u, IloCplex cplex){
this.n = n;
this.c = c;
this.demand = demand;
this.x = x;
this.u = u;
this.cplex = cplex;
}
protected void main() throws IloException {
// Get the current x solution
// double[][] sol = new double[n][n];
// for (int i = 0; i < n; i++) {
// for (int j = 0; j < n; j++) {
// sol[i][j] = cplex.getValue(x[i][j]);
// }
// }
for (int i = 1; i < n; i++) {
for (int j = 1; j < n; j++) {
if (i!=j && demand[i]+demand[j]<=c){
IloLinearNumExpr equation5 = cplex.linearNumExpr();
equation5.addTerm(1.0, u[i]);
equation5.addTerm(-1.0, u[j]);
equation5.addTerm(c, x[i][j]);
rng[i].setExpr(equation5);
rng[i].setBounds(Double.MIN_VALUE, c-demand[j]);
cplex.addLazyConstraint(rng[i]);
}
}
}
for (int i = 1; i < n; i++) {
IloLinearNumExpr equation6 = cplex.linearNumExpr();
equation6.addTerm(1.0, u[i]);
rng[i].setExpr(equation6);
rng[i].setBounds(demand[i], c);
cplex.addLazyConstraint(rng[i]);
}
}
}
As far as I can tell, rng is never initialized in your callback class. So it is always null and as soon as you attempt to set an element in it, you will get that NullPointerException.
Note that you don't even need that array. Instead of
rng[i].setExpr(equation5);
rng[i].setBounds(Double.MIN_VALUE, c-demand[j]);
cplex.addLazyConstraint(rng[i]);
you can just write
IloRange rng = cplex.range(Double.MIN_VALUE, equation5, c - demand[j]);
cplex.addLazyConstraint(rng);
(and similarly for equation6).
Also note that Double.MIN_VALUE is likely not what you want. This gives the smallest representable number larger than 0. I guess what you want is Double.NEGATIVE_INFINITY to specify a range without lower bound. In that case you could also just write
IloRange rng = cplex.le(equation5, c - demand[j]);
I want my program to output this in a certain way, how would I make this possible? So far, my code is giving me the wrong thing.
Here's my .txt file:
ABCDEFGHIJKLMNOPQRSTUVWXYZOOOOOOO
Here's my java file:
import java.io.*;
public class EncryptDecrypt {
public static void encrypt() throws IOException {
BufferedReader in = new BufferedReader(new FileReader("cryptographyTextFile.txt"));
String line = in.readLine();
char[][] table = new char[6][5];
// fill array
for(int i = 0; i < 6; i++) {
for(int j = 0; j < 5; j++) {
while(table[i][j] < 6) {
table[i][j] = line.charAt(j);
}
}
}
// print array
for(int i = 0; i < 6; i++) {
for(int j = 0; j < 5; j++) {
System.out.println(table[i][j] + " ");
}
System.out.println();
}
}
public static void main(String[] args) throws IOException {
encrypt();
}
}
How would I print this .txt file like so:
ABCDE
GHIJK
MNOPQ
STUVW
XYZOO
OOOOO
A couple of problems
see
String line = "ABCDEFGHIJKLMNOPQRSTUVWXYZOOOOOOO";
char[][] table = new char[6][5];
int counter = 0;
// fill array
for(int i = 0; i < 6; i++) {
for(int j = 0; j < 5; j++) {
table[i][j] = line.charAt(counter++); // need to increment through the String
}
}
// print array
for(int i = 0; i < 6; i++) {
for(int j = 0; j < 5; j++) {
System.out.print(table[i][j] + " "); // not println
}
System.out.println();
}
output
A B C D E
F G H I J
K L M N O
P Q R S T
U V W X Y
Z O O O O
Although a more extensible way would be link
String line = "ABCDEFGHIJKLMNOPQRSTUVWXYZOOOOOOO";
String lines [] = line.split("(?<=\\G.....)");
for (String l : lines) {
System.out.println(l);
}
we're supposed to multiply every element in the matrix by a number, in this case "k". not sure what i'm doing wrong but it wont work. HELP! i have edited and added the whole project so far.
public class Matrix {
private int r;//rows
private int c;//columns
private int[][] neo; //2D array
public static void main(String[] args) {
Matrix m1 = new Matrix(3,4);
Matrix m2 = new Matrix(3,4);
System.out.println(m2);
try {
Matrix m3 = m1.multiply(m2);
} catch (Exception e) {
e.printStackTrace();
}
m2.scaleMult(k);
}//main
public Matrix(int row, int column) {
r = row;
c = column;
neo = new int[r][c];
for(int i = 0; i < neo.length; i++) {
for (int j = 0; j < neo[i].length; j++) {
neo[i][j] = (int) (1 + Math.random() * 100);
}//forLoop
}//forLoop
System.out.println(Arrays.toString(neo));
}//Matrix
public Matrix copyMatrix(Matrix m) {
Matrix copy = new Matrix(m.r, m.c);
for (int i = 0; i < r; i++) {
System.arraycopy(this.neo[i], 0, copy.neo[i], 0, this.neo[i].length);
}//forLoop
return copy;
}//copyMatrix
public void scaleMult(int k){
for (int i = 0; i < r; i++)
for (int j = 0; j < c; j++)
this.neo[i][j] * k;
}//scaleMult
public boolean equals(Matrix m2) {
if (this.r != m2.r || this.c != m2.c) {
return false;
}
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
if (this.neo[i][j] != m2.neo[i][j]) {
return false;
}
}
}
return true;
}//equalsMethod
public Matrix multiply(Matrix m2) throws Exception {
if (this.c != m2.r) {
throw new RuntimeException();
}//if
Matrix m3 = new Matrix(this.r, m2.c);
for (int i = 0; i < this.r; i++) {
for (int j = 0; j < m2.c; j++) {
m3.neo[i][j] = 0;
for (int k = 0; k < this.c; k++) {
m3.neo[i][j] += this.neo[i][k] * m2.neo[k][j];
}//forK
}//forJ
}//forI
return m3;
}//multiplyMethod
}//class
Change your scaleMult method to this and it should work:
public void scaleMult(int k) {
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
this.neo[i][j] *= k;
// you forgot to assign the value, basically we multiply neo[i][j] by k and make neo[i][j] receive that value
// making this.neo[i][j] = this.neo[i][j] *k; would work as well
}
}
}//scaleMult
Also, based on the example you provided on your main method, your code will launch an exception on the multiply method, because as you specified, you can only multiply two matrixes if one's columns amount is equal to the other's row amount. Other than that, I would advise on creating a new class just for your main method.
If your question is multiply a matrix by a number, then here is a very simple example.
public static void main(String []args){
int[][] a = {{1,2,3},{4,5,6}};
int[][] b=new int[2][3];
int i,j,k=2;
for(i=0;i<2;i++)
for(j=0;j<3;j++)
b[i][j]=a[i][j]*k;
for(i=0;i<2;i++)
for(j=0;j<3;j++)
System.out.println(b[i][j]);
}
There must be some array variable on left which should be assigned the multiplied value.
Do this helped? If not, please post your complete code.
I have a class which is :
public class CCTest {
public double f;
public double[][][] x;
public double counter;
};
and i have assigned random number to x,
CCTest[] cls = new CCTest[5];
for (int i = 0; i < cls.length; i++) {
cls[i] = new CCTest();
}
for (int i = 0; i < (Size = 5); i++) {
cls[i].x = new double[this.c][this.D][this.Size];
for (int j = 0; j < this.D; j++) {
cls[i].x = getRandomX(this.c, this.D, this.Size);
}
}
then I tried to display the result using :
public static void display(double[][][] array) {
int rows = array.length;
int columns = array[0].length;
int depth = array[0][0].length;
for (int d = 0; d < depth; d++) {
for (int r = 0; r < rows; r++) {
for (int c = 0; c < columns; c++) {
System.out.print(array[r][c][d] + " ");
}
System.out.println();
}
System.out.println();
}
}
The Random Generation method is :
public static double[][][] getRandomX(int x, int y, int z) {
double[][][] result = new double[x][y][z];
Random r = new Random();
for (int i = 0; i < z; i++) {
for (int j = 0; j < y; j++) {
for (int k = 0; k < x; k++) {
result[k][j][i] = r.nextDouble();
}
}
}
return result;
}
but the output is empty [] , any idea please
The inner loop : for (int j = 0; j < this.D; j++) {...} is useless so you can remove this.The display and getRandomX() functions are fine. Try this in main , works in my environment:
CCTest[] cls = new CCTest[5];
for (int i = 0; i < cls.length; i++) {
cls[i] = new CCTest();
}
for (int i = 0; i < (Size = 5); i++) {
cls[i].x = new double[c][D][S];
cls[i].x = getRandomX(c, D, S);
}
for (int i = 0; i < (Size = 5); i++) {
display(cls[0].x);
}
Your display method should rather look like:
public static void display(double[][][] array) {
for (int x = 0; x < array.length; x++) {
for (int y = 0; y < array[x].length; y++) {
for (int z = 0; z < array[x][y].length; z++) {
System.out.println(array[x][y][z]);
}
}
}
}
There is another question which comes to my mind. What is getRandomX? You haven't shown us. I'd use the following:
public static double[][][] getRandom3DArray(double[][][] array) {
Random r = new Random();
for (int x = 0; x < array.length; x++) {
for (int y = 0; y < array[x].length; y++) {
for (int z = 0; z < array[x][y].length; z++) {
array[x][y][z] = r.nextDouble();
}
}
}
return array;
}
You're mistaking rows with depth in your display.
I am trying to create a simple word search for a class assignment, and I have managed to figure out how to search east (from left to right) and west(right to left). But I am having trouble trying to figure out how to search south (top to bottom).
The code that I have works for one file that I read in but the second file returns an ArrayIndexOutOfBoundsException. Is there anything that is specific in my code that would make it un-scalable?
My corrected code looks like this:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
import wordSeek.GameBoard;
public class WordGame {
private char[][] letters;
GameBoard gb;
public static void main(String[] args) {
WordGame wg = new WordGame();
wg.play();
}
public WordGame() {
letters = readLettersFromFile();
gb = new GameBoard(letters);
}
private void play() {
Scanner s = new Scanner(System.in);
String word;
do {
System.out.println("Enter word to find: ");
word = s.next();
// reset all highlighted tiles
gb.reset();
search(word);
} while (!word.equals("QUIT"));
gb.dispose();
}
// Nothing to be done above
// Complete all the methods below
private char[][] readLettersFromFile() {
// From the data in the file Letters.txt determine the size (number of
// rows and number of columns) for the letters array
int rowCount = 0;
int colCount = 0;
char c;
File file = new File("resources/Places.txt");
Scanner fileScanner = null;
try {
fileScanner = new Scanner(file);
}
catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
ArrayList<String> data = new ArrayList<String>();
while(fileScanner.hasNextLine())
{
String line = fileScanner.nextLine();
data.add(line);
}
fileScanner.close();
rowCount = data.size();
colCount = data.get(0).trim().length()/2+1;
// Instantiate a two dimensional array of characters of the appropriate
// size
letters = new char [rowCount][colCount];
// Populate the array with the letters in Letters.txt
for (int i = 0; i < rowCount; i++) {
String line = data.get(i);
int pos = 0;
for (int j = 0; j < colCount; j++) {
letters[i][j] = line.charAt(pos);
pos += 2;
}
}
// return the array
return letters;
}
private void search(String word) {
System.out.println("Searching for " + word);
//Call the other search methods below as needed
searchIterativeEast(word);
searchIterativeWest(word);
searchIterativeSouth(word);
searchIterativeNorth(word);
}
//The following four methods must employ ITERATION to search the game board
private boolean searchIterativeEast(String word) {
int k = 0;
for (int i = 0; i < letters.length; i++)
{
for (int j = 0; j < letters[i].length; j++) {
if (word.charAt(k) == letters[i][j]) {
k++;
}
else {
k = 0;
}
if (k == word.length()) {
for (int col = j - k + 1; col <= j; col++) {
gb.highlight(i, col);
}
return true;
}
}
}
return false;
}
private boolean searchIterativeWest(String word) {
String reversedWord = "";
for (int i = word.length() - 1; i != -1; i--)
{
reversedWord += word.charAt(i);
}
int k = 0;
for (int i = 0; i < letters.length; i++)
{
for (int j = 0; j < letters[i].length; j++) {
if (reversedWord.charAt(k) == letters[i][j]) {
k++;
}
else {
k = 0;
}
if (k == reversedWord.length()) {
for (int col = j - k + 1; col <= j; col++) {
gb.highlight(i, col);
}
return true;
}
}
}
return false;
}
private boolean searchIterativeSouth(String word) {
int k = 0;
int store = letters[0].length;
for (int j = 0; j < letters[store].length; j++)
{
for (int i = 0; i < letters.length; i++)
{
if (word.charAt(k) == letters[i][j])
{
k++;
}
else
{
k = 0;
}
if (k == word.length())
{
for(int row = i-k+1 ; row <= i; row++)
{
gb.highlight(row, j);
}
return true;
}
}
}
return false;
}
private boolean searchIterativeNorth(String word) {
String reversedWord = "";
for (int i = word.length() - 1; i != -1; i--)
{
reversedWord += word.charAt(i);
}
int k = 0;
int store = 0;
for(int i = 0; i < letters.length; i++)
{
store = letters[i].length;
}
for (int j = 0; j < letters[store].length; j++)
{
for (int i = 0; i < letters.length; i++)
{
if (reversedWord.charAt(k) == letters[i][j])
{
k++;
}
else
{
k = 0;
}
if (k == reversedWord.length())
{
for(int row = i-k+1 ; row <= i; row++)
{
gb.highlight(row, j);
}
return true;
}
}
}
return false;
}
The Gameboard for the first file (Animals.txt) looks like: 5X4 2d Array
X C A T
P A L Q
I R B U
G P X N
G O D W
Output highlights CARP.
The Gameboard for the second file (Places.txt) looks like: 11x15 2d Array
O M J G D A X V C S Q N K I F
D A X V T Q O M J H A A H F C
A Y W U R P N L F E I T A L Y
J N H N E T H E R L A N D S F
D B I Z X V T O A R Q O A Y K
M K I A H F K R N O D B N N I
N Z Y W P H T V C G C T A A N
R A Q O T S N L E K K I C M G
I H P U U F D C A Z D O X R D
X W O A L E U Z E N E V N E O
V S U S J R Q L I Z A R B G M
The return statement goes outside of the for loop, otherwise you will only highlight the first letter.
...
for (int row = j-k+1; row <=i; row++ )
{
//gb.highlight() just calls a method that highlights the letters.
gb.highlight(row, j);
//return true;
}
return true;
...
for (int j = 0; j < letters[i].length; j++)
instead of
for (int j = 0; j < letters.length; j++)