This question already has answers here:
Algorithm to generate a crossword [closed]
(13 answers)
Closed 6 years ago.
I am working on cross word algorithm to develop a word app. After doing a lot of googling or search on StackOverflow, I was able to reach this point. But yet I am not able to understand the right implementation for algorithm in Java. Below is the class I used.
public class Crosswords {
char[][] cross;
int rows;
int cols;
char[][] numberGrid;
boolean startword;
final char DEFAULT = ' ';
public Crosswords() {
rows = 50;
cols = 50;
cross = new char[rows][cols];
numberGrid = new char [rows][cols];
for (int i = 0; i < cross.length;i++){
for (int j = 0; j < cross[i].length;j++){
cross[i][j] = DEFAULT;
}
}
}
public Crosswords(int ros, int colls) {
rows = ros;
cols = colls;
cross = new char[rows][cols];
numberGrid = new char [rows][cols];
for (int i = 0;i < cross.length; i++){
for (int j = 0; j < cross[i].length; j++){
cross[i][j] = DEFAULT;
}
}
}
public String toString() {
String s = new String();
//String d = new String();
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++){
s = s + cross[i][j] + " ";
}
s = s + "\n";
}
return s;
}
public void addWordh(String s, int r, int c) {
int i = 0;
int j = 0;
boolean b = true;
boolean intersectsWord = true;
if (s.length() > cols) {
System.out.println(s + " is longer than the grid. Please try another word.");
return;
}
if (c + s.length() > cols) {
System.out.println(s + " is too long. Please try another word.");
return;
}
if ((r - 2) >= 0) {
if ((cross[r - 1][c - 1 + s.length()] == DEFAULT) || (cross[r - 1][c - 1 + s.length()] == '*')) {
intersectsWord = false;
}
else { intersectsWord = true;}
if (intersectsWord == true) {
System.out.println("The word " + s + " intersects the beginning of another word!");
return;
}
}
for (i = 0; i < s.length(); i++) {
if ((cross[r - 1][c - 1 + i] == DEFAULT) || (cross[r - 1][c - 1 + i] == s.charAt(i))) {
b = true;
}
else {
b = false;
System.out.println("Unable to add " + s + ". Please try another word.");
return;}
}
if (b == true) {
if ((s.length() <= cols) && (c + s.length() <= cols) &&
(cross[r - 1][c - 1] == s.charAt(0)) || (cross[r - 1][c - 1] == DEFAULT)) {
while (j < s.length()) {
cross[r - 1][c - 1 + j] = s.charAt(j);
if (j==0){
startword = true;
}
cross[rows - 1 - (r - 1)][cols - 1 - (c - 1 + j)] = '*';
j++;
}
}
}
}
public void addWordv(String s, int r, int c) {
int i = 0;
int j = 0;
boolean b = true;
boolean intersectsWord = true;
if (s.length() > rows) {
System.out.println(s + " is longer than the grid. Please try another word.");
}
if (r + s.length() > rows) {
System.out.println(s + " is too long. Please try another word.");
}
else {
if ((r - 2) >= 0) {
if ((cross[r - 2][c - 1] == DEFAULT) || (cross[r - 2][c - 1] == '*')) {
intersectsWord = false;
}
else { intersectsWord = true;}
if (intersectsWord == true) {
System.out.println("The word " + s + " intersects the end of another word!");
return;
}
}
if ((cross[r - 1 + s.length()][c - 1] == DEFAULT) || (cross[r - 1 + s.length()][c - 1] == '*')) {
intersectsWord = false;
}
else { intersectsWord = true;}
if (intersectsWord == true) {
System.out.println("The word " + s + " intersects the end of another word!");
return;
}
for (i = 0; i < s.length(); i++) {
if ((cross[r - 1 + i][c - 1] == DEFAULT) || (cross[r - 1 + i][c - 1] == s.charAt(i))) {
b = true;
}
else {
b = false;
System.out.println("Unable to add " + s + ". Please try another word.");
return;}
}
if (b == true) {
if ((s.length() <= rows) && (r + s.length() <= cols) &&
(cross[r - 1][c - 1] == s.charAt(0)) || (cross[r - 1][c - 1] == DEFAULT)) {
while (j < s.length()) {
cross[r - 1 + j][c - 1] = s.charAt(j);
if (j==0){
startword = true;
}
cross[rows - 1 - (r - 1 + j)][cols - 1 - (c - 1)] = '*';
j++;
}
}
}
}
}
public void setNumberGrid(){
numberGrid = new char [rows][cols];
for (int i = 0; i < cross.length; i++){
for (int j=0; j < cross[rows].length; j++){
if (cross[i][j] == DEFAULT){
numberGrid[i][j] = (char) 0;
}
else if (startword == true){
numberGrid[i][j] = (char) -2;
}
else {
numberGrid[i][j] = (char) -1;
}
}
int count = 1;
for (i=0; i < cross.length; i++){
for (int j=0; j < cross[rows].length; j++){
if (numberGrid[i][j] == -2){
numberGrid[i][j] = (char)count;
count++;
}
}
}
}
}
public String printNumberGrid() {
for (int i=0; i < cross.length; i++){
for (int j=0; j < cross[rows].length; j++){
if (numberGrid[i][j] == (char)-1){
numberGrid[i][j] = ' ';
}
else if (numberGrid[i][j] == (char)0){
numberGrid[i][j] = '#';
}
}
}
String d = new String();
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++){
d = d + numberGrid[i][j] + " ";
}
d = d + "\n";
}
return d;
}
public static void main(String[] args) {
Crosswords g = new Crosswords();
g.addWordv("rawr", 4, 5);
g.addWordh("bot", 5, 4);
g.addWordv("raw", 7, 5);
g.addWordh("cat", 4, 5);
g.addWordh("bass", 6, 10);
System.out.println(g);
Crosswords c = new Crosswords(20, 20);
c.addWordh("HELLO", 1, 1);
c.addWordv("HAPLOID", 1, 1);
c.addWordh("COMPUTER", 3, 12);
c.addWordv("CAT", 2, 11);
c.addWordv("WOAH", 2, 20);
c.addWordh("PARKING", 20, 5);
c.addWordv("ARK", 17, 6);
c.addWordh("AHOY", 6, 18);
c.addWordv("AHOY", 18, 10);
c.addWordv("ADVANTAGE", 2, 12);
c.addWordv("INTERNAL", 2, 18);
c.addWordh("BANTER", 7, 11);
c.addWordv("BEAGLE", 5, 12);
c.addWordh("BASE", 8, 3);
c.addWordv("BALL", 8, 3);
c.addWordh("LEFT", 10, 3);
c.addWordv("SAFE", 8, 5);
System.out.print(c);
}
}
As you can see in Main method that i am adding the words but also giving the row and column number to place the words like c.addWordv("Safe",8,5); where 8 and 5 is column number.
Now Question is how can i implement cross word algorithm which just take words and place them on board randomly without taking the row and column numbers.
Thanks in advance
EDIT:
I want to modify this class algo the way that i dont have to give away the rows and columns number..
//Pseudo Code
If the crossword size is maxSize and any word's length is stored in wordLength ,then you can use random method as below
int maxSize=20;
int wordLength=4;
Random random =new Random();
int r,c;
//for horizontal
r=random.nextInt(maxSize-wordLength);
c=random.nextInt(maxSize);
//for vertical
r=random.nextInt(maxSize);
c=random.nextInt(maxSize-wordLength);
You can store the row and column and generate the new one if its already present.
Related
I'm doing the Conway's game of life. I'm pretty sure I'm close to finished, but when I run it, I get Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
at game.of.life.GameOfLife.generation(GameOfLife.java:77)
at game.of.life.GameOfLife.main(GameOfLife.java:32)
Java Result: 1
I'm assuming when the method that checks neighbors at the edges of the array, there's nothing there so it dies or something. I just don't know how to make it so that doesn't happen. Does anyone have any thoughts? Code below.
package game.of.life;
import java.util.Scanner;
public class GameOfLife {
static boolean[][] current = new boolean[10][10];
static boolean[][] old = new boolean[10][10];
static int population = 10;
public static void main(String[] args) {
String a = " # ";
String b = " ' ";
int choice = 9;
int gencount = 0;
Scanner input = new Scanner(System.in);
System.out.print("Choose population density. i.e. 10 = 10%: ");
population = input.nextInt();
populate();
copy();
for(int r = 0; r < current.length; r++){
for(int c = 0; c < current[r].length; c++){
if(current[r][c] == true){
System.out.print(a);
}
else
System.out.print(b);
}
System.out.println();
}
System.out.print("Generation " + gencount + ".");
while(choice != 0){
System.out.print("Make a selection: 1 - Advance Generation 0 - Exit");
choice = input.nextInt();
if(choice == 1){
generation();
for(int r = 0; r < current.length; r++){
for(int c = 0; c < current[r].length; c++){
if(current[r][c] == true){
System.out.print(a);
}
else
System.out.print(b);
}
System.out.println();
}
copy();
gencount += 1;
System.out.println("Generation" + gencount + ".");
}
}
}
private static void generation(){
for(int r = 0; r < old.length; r++){
for(int c = 0; c < old[r].length; c++){
if (old[r][c] == true){
int neighbors = 0;
if(old[r + 1][c] == true)
neighbors += 1;
if(old[r - 1][c] == true)
neighbors += 1;
if(old[r][c + 1] == true)
neighbors += 1;
if(old[r][c - 1] == true)
neighbors += 1;
if(old[r + 1][c + 1] == true)
neighbors += 1;
if(old[r + 1][c - 1] == true)
neighbors += 1;
if(old[r - 1][c - 1] == true)
neighbors += 1;
if(old[r - 1][c + 1] == true)
neighbors += 1;
if(neighbors != 3 || neighbors != 2)
current[r][c] = false;
}
else if(old[r][c] == false){
int neighbors = 0;
if(old[r + 1][c] == true)
neighbors += 1;
if(old[r - 1][c] == true)
neighbors += 1;
if(old[r][c + 1] == true)
neighbors += 1;
if(old[r][c - 1] == true)
neighbors += 1;
if(old[r + 1][c + 1] == true)
neighbors += 1;
if(old[r + 1][c - 1] == true)
neighbors += 1;
if(old[r - 1][c - 1] == true)
neighbors += 1;
if(old[r - 1][c + 1] == true)
neighbors += 1;
if(neighbors == 3)
current[r][c] = true;
}
}
}
}
private static void populate(){
for(int r = 0; r < current.length; r++){
for(int c = 0; c < current[r].length; c++){
int q = (int)(Math.random() * 100);
if(q < population){
current[r][c] = true;
}
else{
current[r][c] = false;
}
}
}
}
private static void copy(){
for(int r = 0; r < old.length; r++){
for(int c = 0; c < old[r].length; c++)
old[r][c] = current[r][c];
}
}
}
If anyone can help me out it would be much appreciated.
When r is 0, this one is not valid: old[r - 1][c].
Thus you get the exception you posted.
I suggest you simplify it like this.
boolean isValidPosition(int r, int c){
return
0 <= r && r < N &&
0 <= c && c < M;
}
int getNeighboursCount(boolean[][] old, int r, int c){
int neighbors = 0;
for (int i=-1; i<=1; i++){
for (int j=-1; j<=1; j++){
if (i!=0 || j!=0){
if (isValidPosition(r + i, c + j)){
if(old[r + i][c + j])
{
neighbors++;
}
}
}
}
}
return neighbors;
}
As I can see, you basically have two choices:
apply finite bounds, that is, for the cells in the first and last columns and rows, you implement an additional check when counting the number of 'living' neighbours.
apply periodic bounds, that is, the cells on the leftmost column and the cells on the rightmost column are considered as neighbours. With the help of modular arithmetic, these cells don't need to be handled separately from others.
With some help, I've created a temporary 2D array called nextStep to handle the new cells that come to life in the colony of cells-but for some reason my code is still birthing and killing cells in the same generation, rather than applying the necessary changes in the next generation. Any help would be very appreciated.
public void updateColony() {
nextStep = new int[colony.length][colony[0].length];
for (int i = 0; i < colony.length; i++) {
for (int j = 0; j < colony[i].length; j++) {
evolution(i, j, colony);
}
}
colony = nextStep;
}
public void setCellAlive (int row, int col){
if (row <= numberRows){
nextStep [row][col] = 1;
}else{
System.out.println ("Index out of range.");
}
}
public void setCellDead (int row, int col){
if (row <= numberRows){
nextStep [row][col]=0;
}else{
System.out.println ("Index out of range.");
}
}
private void evolution(int i, int j, int [][] colony) {
int left = 0, right = 0, up = 0, down = 0;
int UpperLeft = 0, UpperRight = 0, LowerLeft = 0, LowerRight = 0;
if (j < colony.length - 1) {
right = colony[i][j + 1];
if(i>0)
UpperRight = colony[i - 1][j + 1];
if (i < colony.length - 1)
LowerRight = colony[i + 1][j + 1];
}
if (j > 0) {
left = colony[i][j - 1];
if (i > 0)
UpperLeft = colony[i - 1][j - 1];
if (i< colony.length-1)
LowerLeft = colony[i + 1][j - 1];
}
if (i > 0)
up = colony[i - 1][j];
if (i < colony.length - 1)
down = colony[i + 1][j];
int sum = left + right + up + down + UpperLeft + UpperRight
+ LowerLeft
+ LowerRight;
if (colony[i][j] == 1) {
if (sum < 2)
setCellDead (i,j);
if (sum > 3)
setCellDead(i,j);
}
else {
if (sum == 3)
setCellAlive (i,j);
}
}
Check if the matrix is folded from.
The test should make:
image
The code always returns false and it is unclear to me why. What's wrong with the code?
the code:
public class test1 {
public static void main(String[] args) {
int[][] mat = { { 1, 7, 9 }, { 2, 9, 7 }, { 9, 2, 1 } };
boolean flag = true;
for (int i = 0; i < mat.length; i++) {
for (int j = 0; j < mat.length; j++) {
System.out.print("[" + mat[i][j] + "]");
}
System.out.println();
}
for (int i = mat.length - 1; i > -1; i--) {
for (int j = mat.length - 1; j > -1; j--) {
if (i == j) {
j--;
}
if (mat[i][j] != mat[j][i]) {
flag = false;
System.out.println("mat[i][j]" + mat[i][j] + " " + i + " "
+ j);
j = -1;
i = -1;
}
}
}
if (flag == false) {
System.out.println("Not first folded matrix");
} else {
System.out.println("First folded matrix");
}
}
}
thank you
You can use this function:
public static boolean isFolded(int[][] mat){
for (int i = 0; i < mat.length; i++) {
for (int j = 0; j < mat.length; j++) {
if (i == j) {
continue;
}
if (mat[i][j] != mat[mat.length - 1 - j][mat.length - 1 - i]) {
System.out.println("mat[i][j] " + mat[i][j] + " i:" + i + " j:"
+ j);
return false;
}
}
}
return true;
}
Call it in you main like:
flag = isFolded(mat);
package edu.bsu.cs121.mamurphy;
import java.util.*;
import java.io.*;
import javax.swing.*;
import java.awt.*;
// Maurice Murphy
// CS121
// 10/17/15
public class GameOfLifeMain extends JFrame {
// Intitial reading and printing of the world
public GameOfLifeMain() {
super("Game of Life");
setSize(600, 445);
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(1, 2));
Test test1 = new Test();
test1.setBackground(Color.LIGHT_GRAY);
panel.add(test1);
setContentPane(panel);
setVisible(true);
Temp one = new Temp(test1);
one.start();
}
public static void main(String[] asd) {
new GameOfLifeMain();
System.out.println();
}
}
class Temp extends Thread {
Test anim;
public Temp(Test anim) {
this.anim = anim;
}
public void run()// for each instance of test begin will be executed
{
anim.begin();
}
}
class Test extends JPanel
{
final static int numOfRow = 25, numOfCol = 75;
final static char DOT = '.';
static char[][] grid = new char[numOfRow + 2][numOfCol + 2];
static char[][] nextgrid = new char[numOfRow + 2][numOfCol + 2];
boolean sameFlag;
boolean blankFlag;
public static void init(char[][] grid, char[][] nextgrid) {
for (int numOfRow = 0; numOfRow <= numOfRow + 1; numOfRow++) {
for (int numOfCol = 0; numOfCol <= numOfCol + 1; numOfCol++) {
grid[numOfRow][numOfCol] = DOT;
nextgrid[numOfRow][numOfCol] = DOT;
}
}
}
public static void pause() {
try {
Thread.currentThread();
Thread.sleep(1000L);
} catch (InterruptedException e) {
}
}
public void begin() {
init(grid, nextgrid);
read(grid);
repaint(); // calls paintComponent
pause();
while (sameFlag == true && blankFlag == false) {
nextGen(grid, nextgrid);
}
}
public static void read(char[][] grid) {
Scanner world = new Scanner(System.in);
System.out.println("Type the file name of the world you'd like to create.");
String fileName = world.nextLine();
{
try {
world = new Scanner(new File(fileName));
} catch (Exception ex) {
System.out.println("Please insert a valid file name.");
}
;
for (int numOfRow = 1; numOfRow <= numOfRow; numOfRow++) {
String s = world.next();
for (int numOfCol = 1; numOfCol <= numOfCol; numOfCol++) {
grid[numOfRow][numOfCol] = s.charAt(numOfCol - 1);
}
}
}
}
public void print(Graphics g) {
int x, y;
y = 20;
for (int numOfRow = 1; numOfRow <= numOfRow; numOfRow++) {
x = 20;
for (int numOfCol = 1; numOfCol <= numOfCol; numOfCol++) {
g.drawString("" + grid[numOfRow][numOfCol], x, y);
x = x + 7;
}
y = y + 15;
}
}
public static int neighbors(char[][] grid, int r, int c) {
// counts the # of closest neighbors that are X's
int count = 0;
for (int numOfRow = r - 1; numOfRow <= r + 1; numOfRow++) {
for (int numOfCol = c - 1; numOfCol <= c + 1; numOfCol++) {
if (grid[numOfRow][numOfCol] == 'X') {
count++;
}
}
}
if (grid[r][c] == 'X') {
count = count - 1;
}
return count;
}
public static void nextGen(char[][] grid, char[][] nextgrid) {
for (int numOfRow = 1; numOfRow <= numOfRow; numOfRow++) {
for (int numOfCol = 1; numOfCol <= numOfCol; numOfCol++) {
if (grid[numOfRow][numOfCol] == 'X') {
int count = 0;
{
if (grid[numOfRow][numOfCol - 1] == 'X')
count = count + 1;
if (grid[numOfRow][numOfCol + 1] == 'X')
count = count + 1;
if (grid[numOfRow - 1][numOfCol] == 'X')
count = count + 1;
if (grid[numOfRow - 1][numOfCol - 1] == 'X')
count = count + 1;
if (grid[numOfRow - 1][numOfCol + 1] == 'X')
count = count + 1;
if (grid[numOfRow + 1][numOfCol - 1] == 'X')
count = count + 1;
if (grid[numOfRow + 1][numOfCol] == 'X')
count = count + 1;
if (grid[numOfRow + 1][numOfCol + 1] == 'X')
count = count + 1;
}
if (count == 2 || count == 3) {
nextgrid[numOfRow][numOfCol] = 'X';
} else
nextgrid[numOfRow][numOfCol] = DOT;
}
if (grid[numOfRow][numOfCol] == DOT) {
int count1 = 0;
{
if (grid[numOfRow][numOfCol - 1] == 'X')
count1 = count1 + 1;
if (grid[numOfRow][numOfCol + 1] == 'X')
count1 = count1 + 1;
if (grid[numOfRow - 1][numOfCol] == 'X')
count1 = count1 + 1;
if (grid[numOfRow - 1][numOfCol - 1] == 'X')
count1 = count1 + 1;
if (grid[numOfRow - 1][numOfCol + 1] == 'X')
count1 = count1 + 1;
if (grid[numOfRow + 1][numOfCol - 1] == 'X')
count1 = count1 + 1;
if (grid[numOfRow + 1][numOfCol] == 'X')
count1 = count1 + 1;
if (grid[numOfRow + 1][numOfCol + 1] == 'X')
count1 = count1 + 1;
}
if (count1 == 3)
nextgrid[numOfRow][numOfCol] = 'X';
}
}
}
}
public static void copy(char[][] grid, char[][] nextgrid) {
for (int i = 0; i < numOfRow + 1; i++) {
for (int j = 0; j < numOfCol + 1; j++) {
grid[i][j] = nextgrid[i][j];
}
}
}
public static boolean isEmpty(char[][] grid, char[][] nextgrid) {
boolean blankFlag = true;
for (int i = 0; i < numOfRow + 1; i++) {
for (int j = 0; j < numOfCol + 1; j++) {
if (grid[i][j] != DOT) {
blankFlag = false;
}
}
}
return blankFlag;
}
public static boolean isSame(char[][] grid, char[][] nextgrid) {
boolean sameFlag = false;
for (int i = 0; i < numOfRow + 1; i++) {
for (int j = 0; j < numOfCol + 1; j++) {
if (grid[i][j] == nextgrid[i][j]) {
sameFlag = true;
break;
}
}
}
return sameFlag;
}
public void paintComponent(Graphics g) {
super.paintComponent(g);// erases panel Contents
g.setColor(Color.black);
if (sameFlag == false && blankFlag == false) {
print(g);// or whatever method you use to print the world
} else {
if (sameFlag == true) {
g.drawString("The worlds are repeating!", 10, 250);
}
if (blankFlag == true) {
g.drawString("The world is blank!", 10, 250);
}
}
}
}
Sorry about not putting in all the code.
Any help is greatly appreciated.
I have figured out the issue thanks to the help of all your answers. For whatever reason, Eclipse wasn't reading that the files were in the folder with the project, so I simply deleted and readded the files (in the same place mind you) and all of a sudden it started working again.
Now my current issue is to figure out why my program isn't proceeding onto the next generation of life.
Specifically, I need to be able to ask the user if they want to continue onto the next generation of life.
The output should be Do you want to go to the next generation? Type y for yes, type n to quit the program.
Part of your problem is that you are catching a general Exception, so anything could be going wrong. You should print the stack trace from your Exception to help in debugging this issue, as it will give you more precise info on where the error actually is. I.e., is it in opening the File or is it in creating a Scanner from the open File. Hopefully you are seeing why should not catch general exceptions.
Note this is only for debugging, though, as printing the stack trace is not good general practice.
File must located in directory project.
You see error message replace your source:
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
you probably need to provide the full path of the file. meaning the exact location of where the file is on your system.
also, it would be easier to have the file as a resource in your project. this way, you can easily load it as a resource by name as
ClassLoader classloader = Thread.currentThread().getContextClassLoader();
InputStream is = classloader.getResourceAsStream("test.txt");
package edu.bsu.cs121.mamurphy;
import java.util.*;
import java.io.*;
import javax.swing.*;
import java.awt.*;
// Maurice Murphy
// CS121
// 10/17/15
public class GameOfLifeMain extends JFrame {
// Intitial reading and printing of the world
public GameOfLifeMain() {
super("Game of Life");
setSize(600, 445);
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(1, 2));
Test test1 = new Test();
test1.setBackground(Color.LIGHT_GRAY);
panel.add(test1);
setContentPane(panel);
setVisible(true);
Temp one = new Temp(test1);
one.start();
}
public static void main(String[] asd) {
new GameOfLifeMain();
System.out.println();
}
}
class Temp extends Thread {
Test anim;
public Temp(Test anim) {
this.anim = anim;
}
public void run()// for each instance of test begin will be executed
{
anim.begin();
}
}
class Test extends JPanel
{
final static int numOfRow = 25, numOfCol = 75;
final static char DOT = '.';
static char[][] grid = new char[numOfRow + 2][numOfCol + 2];
static char[][] nextgrid = new char[numOfRow + 2][numOfCol + 2];
boolean sameFlag;
boolean blankFlag;
public static void init(char[][] grid, char[][] nextgrid) {
for (int numOfRow = 0; numOfRow <= numOfRow + 1; numOfRow++) {
for (int numOfCol = 0; numOfCol <= numOfCol + 1; numOfCol++) {
grid[numOfRow][numOfCol] = DOT;
nextgrid[numOfRow][numOfCol] = DOT;
}
}
}
public static void pause() {
try {
Thread.currentThread();
Thread.sleep(1000L);
} catch (InterruptedException e) {
}
}
public void begin() {
init(grid, nextgrid);
read(grid);
repaint(); // calls paintComponent
pause();
while (sameFlag == true && blankFlag == false) {
nextGen(grid, nextgrid);
}
}
public static void read(char[][] grid) {
Scanner world = new Scanner(System.in);
System.out.println("Type the file name of the world you'd like to create.");
String fileName = world.nextLine();
{
try {
world = new Scanner(new File(fileName));
} catch (Exception ex) {
System.out.println("Please insert a valid file name.");
}
;
for (int numOfRow = 1; numOfRow <= numOfRow; numOfRow++) {
String s = world.next();
for (int numOfCol = 1; numOfCol <= numOfCol; numOfCol++) {
grid[numOfRow][numOfCol] = s.charAt(numOfCol - 1);
}
}
}
}
public void print(Graphics g) {
int x, y;
y = 20;
for (int numOfRow = 1; numOfRow <= numOfRow; numOfRow++) {
x = 20;
for (int numOfCol = 1; numOfCol <= numOfCol; numOfCol++) {
g.drawString("" + grid[numOfRow][numOfCol], x, y);
x = x + 7;
}
y = y + 15;
}
}
public static int neighbors(char[][] grid, int r, int c) {
// counts the # of closest neighbors that are X's
int count = 0;
for (int numOfRow = r - 1; numOfRow <= r + 1; numOfRow++) {
for (int numOfCol = c - 1; numOfCol <= c + 1; numOfCol++) {
if (grid[numOfRow][numOfCol] == 'X') {
count++;
}
}
}
if (grid[r][c] == 'X') {
count = count - 1;
}
return count;
}
public static void nextGen(char[][] grid, char[][] nextgrid) {
for (int numOfRow = 1; numOfRow <= numOfRow; numOfRow++) {
for (int numOfCol = 1; numOfCol <= numOfCol; numOfCol++) {
if (grid[numOfRow][numOfCol] == 'X') {
int count = 0;
{
if (grid[numOfRow][numOfCol - 1] == 'X')
count = count + 1;
if (grid[numOfRow][numOfCol + 1] == 'X')
count = count + 1;
if (grid[numOfRow - 1][numOfCol] == 'X')
count = count + 1;
if (grid[numOfRow - 1][numOfCol - 1] == 'X')
count = count + 1;
if (grid[numOfRow - 1][numOfCol + 1] == 'X')
count = count + 1;
if (grid[numOfRow + 1][numOfCol - 1] == 'X')
count = count + 1;
if (grid[numOfRow + 1][numOfCol] == 'X')
count = count + 1;
if (grid[numOfRow + 1][numOfCol + 1] == 'X')
count = count + 1;
}
if (count == 2 || count == 3) {
nextgrid[numOfRow][numOfCol] = 'X';
} else
nextgrid[numOfRow][numOfCol] = DOT;
}
if (grid[numOfRow][numOfCol] == DOT) {
int count1 = 0;
{
if (grid[numOfRow][numOfCol - 1] == 'X')
count1 = count1 + 1;
if (grid[numOfRow][numOfCol + 1] == 'X')
count1 = count1 + 1;
if (grid[numOfRow - 1][numOfCol] == 'X')
count1 = count1 + 1;
if (grid[numOfRow - 1][numOfCol - 1] == 'X')
count1 = count1 + 1;
if (grid[numOfRow - 1][numOfCol + 1] == 'X')
count1 = count1 + 1;
if (grid[numOfRow + 1][numOfCol - 1] == 'X')
count1 = count1 + 1;
if (grid[numOfRow + 1][numOfCol] == 'X')
count1 = count1 + 1;
if (grid[numOfRow + 1][numOfCol + 1] == 'X')
count1 = count1 + 1;
}
if (count1 == 3)
nextgrid[numOfRow][numOfCol] = 'X';
}
}
}
}
public static void copy(char[][] grid, char[][] nextgrid) {
for (int i = 0; i < numOfRow + 1; i++) {
for (int j = 0; j < numOfCol + 1; j++) {
grid[i][j] = nextgrid[i][j];
}
}
}
public static boolean isEmpty(char[][] grid, char[][] nextgrid) {
boolean blankFlag = true;
for (int i = 0; i < numOfRow + 1; i++) {
for (int j = 0; j < numOfCol + 1; j++) {
if (grid[i][j] != DOT) {
blankFlag = false;
}
}
}
return blankFlag;
}
public static boolean isSame(char[][] grid, char[][] nextgrid) {
boolean sameFlag = false;
for (int i = 0; i < numOfRow + 1; i++) {
for (int j = 0; j < numOfCol + 1; j++) {
if (grid[i][j] == nextgrid[i][j]) {
sameFlag = true;
break;
}
}
}
return sameFlag;
}
public void paintComponent(Graphics g) {
super.paintComponent(g);// erases panel Contents
g.setColor(Color.black);
if (sameFlag == false && blankFlag == false) {
print(g);// or whatever method you use to print the world
} else {
if (sameFlag == true) {
g.drawString("The worlds are repeating!", 10, 250);
}
if (blankFlag == true) {
g.drawString("The world is blank!", 10, 250);
}
}
}
}
So I am coding this for an assignment in my CS121 java class, and it is for Conway's Game of Life. The idea behind the code is that the user types in a file name (a text file) which has a grid of periods and x's. A period is a dead cell and an x is a living cell.
When I try and type in the file name, it automatically throws me to the exception and says Please insert a valid file name.
If I try and type in the file name again, it gives me this error.
Exception in thread "Thread-2" java.lang.StringIndexOutOfBoundsException: String index out of range: 9
at java.lang.String.charAt(Unknown Source)
at edu.bsu.cs121.mamurphy.Test.read(GameOfLifeMain.java:103)
at edu.bsu.cs121.mamurphy.Test.begin(GameOfLifeMain.java:79)
at edu.bsu.cs121.mamurphy.Temp.run(GameOfLifeMain.java:46)
So the one answer I have gotten says that I need to put my prompt asking the user for the file name within a loop that only happens when the file name successfully opens. How can I go about doing this?
After you catch the exception trying to open the file, your code continues into the loop to read from the file (which was not opened). Since the scanner (world) is still assigned to System.in, your next attempt to enter the file name is processed as the first row in the file. Since the name you input is shorter than the expected number of columns, you get an index out of range exception at 's.charAt(numOfCol - 1)'
You need to put your prompt for the file name in a loop, which exits only when the file is successfully opened.