Sudoku generator: ArrayOutOfBoundsException - java

In this project, I am trying to write a program that creates a 9x9 Sudoku board with 9 3x3 subgrids, along with a header row and column that lists the letters a to i. The program compiles correctly, but when I hit run, it gives the following error:
java.lang.ArrayIndexOutOfBoundsException: 0
at Sudoku.main(Sudoku.java:218)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at `enter code here`edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:272)
Now, when I submitted this, the grading program stated that my print(), rowsComplete(), columnsComplete(), and isComplete() methods were incorrect, and that my main() was throwing a java.util.NoSuchElementException. I am confused as to why this is happening. Here is my code for Java, as well as notes on what exactly the methods are supposed to be doing.
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class Sudoku
{
public static final int SIZE = 9;
public static final int SUBGRID = 3;
public int[][] game;
public int[][] originalGame;
public Sudoku(String puzzleFile)
{
try
{
game = new int[SIZE][SIZE];
originalGame = new int[SIZE][SIZE];
File file = new File(puzzleFile);
Scanner in = new Scanner(file);
int i = 0;
int j = 0;
int k;
for (i = 0; i<SIZE; i++){
for (j = 0; j<SIZE; j++){
k = in.nextInt();
game[i][j]=k;
originalGame[i][j] = k;
}
}
}
catch (FileNotFoundException e)
{
System.out.println("FileNotFound: " + e.getMessage());
}
}
public void setZero(int[] array)
{
int i = 0;
for (i = 0; i < array.length; i++)
{
array[i] = 0;
}
}
/**
* This method determines whether the ints 1-9 are present exactly
* once in each row. Sets valSeen[i] = 1 if it sees i. If at any
* point valSeen[i] is already 1, the rows are not complete because of
* duplicate entries.
*
* If game[x][y] == -1, there is a blank entry so the row cannot be complete.
*
* #param valSeen: an array of ints that serve as flags to indicate whether
* their entry has been seen before or not.
*
* returns: true if each digit 1-9 is present in the row exactly once, else false
**/
public boolean rowsComplete(int[] valSeen)
{
int temp;
int k = 0;
for(int rows = 0; rows<SIZE; rows++){
for(int cols = 0; cols<SIZE; cols++){
if(game[rows][cols]==-1)
return false;
temp = game[rows][cols];
valSeen[temp-1]++;
}
for(k=0; k<valSeen.length; k++){
if(valSeen[k]!=1)
return false;
else return true;
}
setZero(valSeen);
}
return true;
}
/**
* This method determines whether the ints 1-9 are present exactly
* once in each column. Sets valSeen[i] = 1 if it sees i. If at any
* point valSeen[i] is already 1, the rows are not complete because of
* duplicate entries.
*
* If game[x][y] == -1, there is a blank entry so the row cannot be complete.
*
* #param valSeen: an array of ints that serve as flags to indicate whether
* their entry has been seen before or not.
*
* returns: true if each digit 1-9 is present in the column exactly once, else false
**/
public boolean columnsComplete(int[] valSeen)
{
int temp;
int k = 0;
for(int cols = 0; cols<SIZE; cols++){
for(int rows = 0; rows<SIZE; rows++){
if(game[rows][cols]==-1)
return false;
temp = game[rows][cols];
valSeen[temp-1]++;
}
for(k=0; k<valSeen.length; k++){
if(valSeen[k]!=1)
return false;
else return true;
}
setZero(valSeen);
}
return true;
}
/**
* This method determines whether the ints 1-9 are present exactly
* once in each subgrid. Sets valSeen[i] = 1 if it sees i. If at any
* point valSeen[i] is already 1, the rows are not complete because of
* duplicate entries.
*
* If game[x][y] == -1, there is a blank entry so the row cannot be complete.
*
* #param valSeen: an array of ints that serve as flags to indicate whether
* their entry has been seen before or not.
*
* returns: true if each digit 1-9 is present in each subgrid exactly once, else false
**/
public boolean subgridsComplete(int[] valSeen)
{
int temp;
for(int rows=0; rows<SIZE; rows+=3){
for (int cols=0; cols<SIZE; cols+=3){
for(int subrows=0; subrows<SUBGRID; subrows++){
for (int subcols=0; subcols<SUBGRID; subcols++){
temp= game[rows+subrows][cols+subcols];
if(temp==-1)
return false;
else
valSeen[temp-1]++;
}
}
for(int k=0; k<valSeen.length; k++){
if(valSeen[k]!=1)
return false;
else return true;
}
setZero(valSeen);
}
}
return true;
}
// Create the array valSeen here. I suggest making it = new int[SIZE+1].
// That way, it will have indexes 0-9, so the ints 1-9 can go into indexes
// 1-9 instead of mapping them to 0-8 by subtracting 1.
// Call rowsComplete(), columnsComplete(), and subgridsComplete().
// Be SURE to initialize valSeen to 0 before each method call by using setZero().
public boolean isComplete()
{
int [] valSeen = new int[SIZE+1];
setZero(valSeen);
if(rowsComplete(valSeen) && columnsComplete(valSeen) && subgridsComplete(valSeen))
return true;
else
return false;
}
public String makeHeader()
{
String header = " ";
for (int x = 97; x<106; x++)
header += ((char)x) + " | " + " ";
return header;
}
/**
* Prints out the grid. Each entry has a space to either side, columns are separated by '|'
* within the grid / between the header and the grid but not externally. See the specification
* for a detailed example. -1 is replaced with '_'.
*
* Remember that 'a' + 1 = 'b'
*
* Prints the grid to standard out.
**/
public void print()
{
System.out.println(makeHeader());
for(int rows=0; rows<SIZE; rows++){
System.out.print(" "+(char)('a'+rows));
for (int cols=0; cols<SIZE; cols++){
if (game[rows][cols]==-1)
System.out.print(" | _");
else
System.out.print(" | "+game[rows][cols]);
}
System.out.println();
}
}
public void move(String row, String col, int val)
{
int rowNumber = ((int)(row.charAt(0)-97));
int columnNumber = ((int)(col.charAt(0)-97));
if(originalGame[rowNumber][columnNumber]==-1)
game[rowNumber][columnNumber]=val;
}
public static void main(String[] args)
{
Sudoku puzzle = new Sudoku(args[0]);
Scanner s = new Scanner(System.in);
System.out.println("");
boolean gameplay = true;
while (gameplay){
puzzle.print();
if(puzzle.isComplete()){
System.out.println("Puzzle Complete!");
gameplay=false;
} else {
System.out.println("Puzzle Incomplete!");
System.out.println("Enter new value <row col val> :");
String rowv = s.next();
String colv = s.next();
int valv = s.nextInt();
puzzle.move(rowv, colv, valv);
}
}
}
}

In main method,
Sudoku puzzle = new Sudoku(args[0]);
Your program need an argument to initialize Sudoku which is being taken from user.
String[] args in main is a array of arguments for program which is given as parameters while starting program.
For you program, you'll have to start your Sudoku.class as
java Sudoku argument
You'll have to run you program with argument, else you'll get java.lang.ArrayIndexOutOfBoundsException: 0

Related

How to find dublicate in an Array

Question
This method will check to see if number 'n'
is in the array of integers stored in the method more than once
It returns true if it is duplicated in the array and false
if not
*/
My code :
for (int i = 0; i < myYears.length; i++) {
for (int j = 0; j < myYears.length; j++) {
// got the duplicate element
System.out.println("Got dublicate");
return true;
}
}
return false;
However all i get is "got Dublicate" no matter the input.
Edit 1
package main;
public class Array1 {
public static void main(String[] args) {
findMoreThanOneInArray(1231); // test will return true
} // end main
/*
* This method will check to see if number 'n'
* is in the array of integers stored in the method more than once
*
* It returns true if it is duplicated in the array and false
* if not
*/
private static boolean findMoreThanOneInArray(int n) {
boolean result = false; // default the search to false
int[] myYears = { 2176, 2311, 2472, 2131, 2046, 2209, 2473, 2364, 2116, 2462, 2405, 2032, 2226, 2223, 2065, 2336, 2372, 2084, 2000, 2074, 2263, 2092, 2485, 2229, 2222, 2369, 2130, 2381, 2487, 2271, 2432, 2011, 2264, 2328, 2251, 2002, 2036, 2410, 2166, 2022, 2064, 2168, 2122, 2409, 2100, 2276, 2361, 2042, 2387, 2211, 2479, 2327, 2044, 2319, 2308, 2265, 2368, 2021, 2325, 2395, 2256, 2086, 2449, 2171, 2098, 2117, 2468, 2338, 2214, 2314, 2204, 2073, 2045, 2295, 2020, 2447, 2233, 2060, 2094, 2383, 2457, 2260, 2224, 2105, 2261, 2405, 2472, 2477, 2253, 2175, 2107, 2441, 2379, 2027, 2386, 2090, 2496, 2280, 2285, 2117 };
/*
* you code goes here
* return true if n is duplicated in the array, false otherwise
*/
for (int i = 0; i < myYears.length; i++) {
for (int j = i + 1 ; j < myYears.length; j++) {
if (myYears[i] == myYears[j]) {
System.out.println("Got dublicate");
return true;
}
}
}
return false;
} // end of method
} // end class
Edit 2
for (int i = 0; i < myYears.length; i++) {
if (myYears[i] == n) {
System.out.println("Got dublicate");
return true;
}
}
System.out.println("false");
return false;
The Edit 2 passed all tests but one, for value of n = 2222; can anyone suggest why ?
Passed all tests but one
I think this is what you are searching for...
int count = 0;
for (int i = 0; i < myYears.length; i++) {
if (myYears[i] == n) {
count++;
}
}
if (count >= 2) {
System.out.println("true");
return true;
}
System.out.println("false");
return false;
This code basically increments the variable count every time by 1 if the given value is found in the array. After the for loop, we check if the variable count is greater or equal to the value 2 (because we need to know if the given number n is appearing more than once)

Why array based queue is not working correctly in java

So we have to use the supplied methods and variables without adding any and no matter what I try I can not get it working. I am extremely new to queues so might be missing something small. Here is my code:
/**
* Int Queue
*/
public class Queue{
/** Max num elements*/
private int numElements;
/** Array to save elements **/
private int elements[];
/** Indice to last element */
private int last;
/** Constructor to init the state object */
Queue(int numElements){
this.numElements = numElements;
this.elements = new int[numElements];
this.last = -1;
}
/** Is empty the queue? */
public boolean isEmpty(){
return (last == -1);
}
/** Is full the queue */
public boolean isFull(){
return (numElements() == this.numElements);
}
/** Insert an element in the queue */
public void enqueue(int element) {
last++;
elements[last]= element;
}
/** Extract the element in the queue.
* There isn't control error */
public int dequeue() {
int elem = elements[0];
for (int x = 0; x < last; x++){
elements[x] = elements [x + 1];
}
last --;
return elem;
}
/** Returns the number of elements in the queue */
public int numElements(){
int number = 0;
for (int x = 0; x < this.last; x++) {
number++;
}
return number;
}
/** Print the elements in the queue*/
public void print(){
System.out.println("\nElements: ");
for(int b:elements){
System.out.println(b);
}
}
public static void main(String args[]){
// test the class
System.out.println("Test the queue class");
Queue que = new Queue(4);
que.enqueue(1);
que.enqueue(4);
que.enqueue(5);
que.print();
que.dequeue();
que.dequeue();
que.print();
} // main
} // Queue
and it outputs:
Test the queue class
Elements:
0
1
4
5
Elements:
4
5
5
5
I am not ale to get it to print the correct options. First it should print 1 4 5 (not the zero) and then it should print 1 and nothing else. All help is apreciated thank you!
I ran your code and I got these results:
Elements:
1
4
5
0
Elements:
5
5
5
0
Which make sense because your internal array will always have the same number of values, as it has a static size (in your case 4).
To fix this, you could rewrite your print method as:
public void print(){
System.out.println("\nElements: ");
for(int i = 0; i < numElements(); i++){
System.out.println(elements[i]);
}
}
Also, change the numElements method:
public int numElements(){
return last + 1;
}
Your problem just lies with how you are printing out your queue. Try this in place of your print:
public void print(){
System.out.println("\nElements: ");
for(int c = 0; c < last+1; c++){
System.out.println(elements[c]);
}
}
Explination
Because you just shift everything forward 1 space when something is dequeued, the data at the end isnt being deleted or "moved forward", its just being copied forward. With your original print, it looks at all of the elements in the entire list, and not just what we are deeming in the queue (anything less than last).

Retrieving data from interface returning enums

I have received a project to solve that uses Enums and I am a bit stuck. It's a tic tac toe game that has enums that store the locations of cells in a 3x3 grid table, and enums that store the state of the cells (empty, X, or O). Plus I have an interface for the GameBoard that returns CellState: getCellState (CellLocation cellLocation);
My task is to write the Consultant interface only and I cannot change anything in the code that was provided to me.
I am struggling to check the status of the Board before each step.
My idea was that X starts the game, I use a for loop for steps and at each step, I check if nrOfSteps%2==0. If yes, I set the cellState to player O. Check if we are at winning position, if we have won or if there's a draw. If not, I will suggest a move.
E.g.
if (nrOfSteps%2!=0){
cState =CellState.OCCUPIED_BY_X;
if (isWon(cState, board)){
throw new IllegalStateException("Player X won!");
} else if (draw(board, locations)){
throw new IllegalStateException("No more empty fields!");
} else
for (int remainingCells = 0; remainingCells <9; remainingCells++) {
if (board.equals(locations[remainingCells]) &&
cState==CellState.EMPTY){
availableCells[index] = locations[remainingCells];
index++;
}
CellLocation cellToTake = availableCells[(int)(Math.random()*
(availableCells.length-1))];
return cellToTake;
}
Now, my problem is that I have tried the following for the isWon method (partial code validating only the first row for now):
private boolean isWon(CellState player, GameBoard board){
if (board.equals(CellLocation.TOP_LEFT) && cState==player &&
board.equals(CellLocation.TOP_CENTRE) && cState==player &&
board.equals(CellLocation.TOP_RIGHT) && cState==player){
return true;
}
return false;
}
But I have realized that the current Status of the board could not be equal to only one cell as I am checking in the above code. And it obviously cannot be equal to 3 different "only one cell"-s. And I am not even sure if I could be checking if the board had only one cell occupied by player X by this:
board.equals (CellLocation.TOP_LEFT) && cState==player
Could someone please give a tip on how I can incorporate both the CellState and CellLocation into one query? Should I use arrays? e.g. CellState[][]?
You can calculate the sums of the cells in the matrix(for each column, row and diagonal). Like this:
import java.io.IOException;
import java.util.Arrays;
import java.util.Random;
public class CrossAndZeros {
private static CellState winner;
private static Enum[][] field = new Enum[3][3];
public static void main(String[] args) throws IOException {
for (int i = 0; i < field.length; i++) {
for (int j = 0; j < field[i].length; j++) {
field[i][j] = CellState.values()[new Random().nextInt(3)];
}
}
for (Enum[] enums : field) {
System.out.println(Arrays.toString(enums));
}
System.out.println();
System.out.println("Winner is found: " + isWinnerFound());
System.out.println(winner == null ? "No winner, GAME OVER" : winner);
}
private static boolean isWinnerFound() {
int[] result = calculate();
int count = 0;
for (int win : result) {
if (win == 3) {
winner = CellState.OCCUPIED_BY_X;
return true;
} else if (win == -12) {
winner = CellState.OCCUPIED_BY_O;
return true;
} else if (win == -9 || win == -2 || win == -3) { // This means that the line is spoilt
count++;
}
}
return count == 8; // If all the lines are spoilt, the game is over
}
private static int[] calculate() {
int[] result = new int[8];
for (int i = 0; i < field.length; i++) {
for (int j = 0; j < field[i].length; j++) {
result[i] += getCellOwner(field[j][i]); // a column
result[i + 3] += getCellOwner(field[i][j]); // a row
}
result[field.length * 2] += getCellOwner(field[i][i]); // diagonal
result[field.length * 2 + 1] += getCellOwner(field[i][field.length - i - 1]); // diagonal
}
System.out.println(Arrays.toString(result));
return result;
}
private static int getCellOwner(Enum cell) {
switch ((CellState) cell) {
case OCCUPIED_BY_O:
return -4;
case OCCUPIED_BY_X:
return 1;
case EMPTY:
default:
return 0;
}
}
public enum CellState {
/**
* this cell is occupied by player X
*/
OCCUPIED_BY_X,
/**
* this cell is occupied by player O
*/
OCCUPIED_BY_O,
/**
* this cell is Empty
*/
EMPTY
}
}
the CellLocation enum:
public enum CellLocation {
/** The Cell in the top row and leftmost column */
TOP_LEFT,
/** The Cell in the top row and centre column */
TOP_CENTRE,
/** The Cell in the top row and rightmost column */
TOP_RIGHT,
/** The Cell in the centre row and leftmost column */
CENTRE_LEFT,
/** The Cell in the centre row and centre column */
CENTRE_CENTRE,
/** The Cell in the centre row and rightmost column */
CENTRE_RIGHT,
/** The Cell in the bottom row and leftmost column */
BOTTOM_LEFT,
/** The Cell in the bottom row and centre column */
BOTTOM_CENTRE,
/** The Cell in the bottom row and rightmost column */
BOTTOM_RIGHT;
}
the CellState enum:
public enum CellState {
/** this cell is occupied by player X */
OCCUPIED_BY_X,
/** this cell is occupied by player O */
OCCUPIED_BY_O,
/** this cell is Empty */
EMPTY;
}

Different Results Running from Eclipse and cmd? Java program--Magic Square

So as the title, I've got different results running my Magic Square program from Eclipse and cmd command. The eclipse one does not make sense.
(The position of sentence "Wrong number..." should be wrong in the eclipse one)
Anyone know how to fix it? Thanks a lot!
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class MagicSquare{
// the two-dimensional array to restore my own magic square.
private int[][] myMagicSquare;
private int n;
public MagicSquare(){
}
/**
* Function: this constructor takes and positive, odd integer parameter to generate a new
* magic square.</br>
* #param n the length of magic square</br>
* #throws IllegalArgumentException for negative or even parameter.
* Preston Jul 5, 20151:15:40 AM</br>
*/
public MagicSquare(int n){
//throws runtime error.
if(!rangeCheck(n)){
throw new IllegalArgumentException("Illegal number");
}else{
// create my magic square array with length of given integer.
this.n = n;
myMagicSquare = new int[n][n];
// generate the magic square.
createMagicSquare();
}
}
/**
*
* Function: this constructor takes a 2D array as a parameter. If the 2D array can generate
* a magic square, then put the values into <i>my magic square</i></br>, if not then throws
* the exception.
* #param newMagicSquare the tested 2D array</br>
* #throws IllegalArgumentException
* Preston Jul 5, 20151:23:10 AM</br>
*/
public MagicSquare(int[][] newMagicSquare){
this.n = newMagicSquare.length;
// determine whether or not the 2D array can generate a magic square.
if(isMagic(newMagicSquare))
myMagicSquare = newMagicSquare;
else
throw new IllegalArgumentException("This is not a magic square");
}
/**
*
* Function:Range check for the input of magic square length</br>
* #param n the length of magic square
* #return true if the length is a positive, odd number</br>
* Preston Jul 5, 20152:53:29 PM</br>
*/
private static boolean rangeCheck(int n){
return !((n>0&&n%2==0)||n<=0);
}
/**
*
* Function: return the magic number of the magic square.</br>
* #return the value magic number.</br>
* Preston Jul 5, 20151:29:02 AM</br>
*/
private int getMagicNumber(){
return (n*(n*n+1))/2;
}
/**
*
* Function: For challenging level: check if all numbers for 1 to n*n only appeared once
* in the given 2D array.</br>
* #param temp the temporary 2D array as parameter.
* #return true if all numbers from 1 to n*n only appeared once</br>
* Preston Jul 5, 20151:30:03 AM</br>
*/
private static boolean noRepeatedNum(int[][] temp){
int n = temp.length;
// Set up the standard Set for comparison.
Set<Integer> standardSet = new HashSet<>();
for(int i=1;i<=n*n;i++){
standardSet.add(i);
}
// the Set made of all numbers from temp. All repeated numbers show only once in Set.
Set<Integer> arraySet = new HashSet<>();
for(int[] x : temp){
for(int a : x){
arraySet.add(a);
}
}
// return if two Sets are equal.
return arraySet.equals(standardSet);
}
/**
*
* Function: Check if the given 2D array can consist a magic square</br>
* #param temp a parameter 2D array.
* #return true if numbers in the parameter array could consist a magic square</br>
* Preston Jul 5, 20151:36:44 AM</br>
*/
private static boolean isMagic(int[][] temp){
//store the return value
boolean isMagic = true;
int tempN = temp.length;
int magicNumber = (tempN*(tempN*tempN+1))/2;
// accumulator for two diagonals
int diagonalOneSum = 0;
int diagonalTwoSum = 0;
// check rows and columns
for(int i=0; i<tempN;i++){
int rowSum = 0;
int columnSum = 0;
for(int j=0;j<tempN;j++){
// single-row sum
rowSum += temp[i][j];
// single-column sum
columnSum += temp[j][i];
}
if(rowSum!=magicNumber||columnSum!=magicNumber){
isMagic = false;
// return false immediately if there's inequality. Save calculations and performance.
return isMagic;
}
}
// counter for the second diagonal
int diagonalTwoCounter = tempN-1;
// sum of two diagonals
for(int i=0;i<temp.length;i++){
diagonalOneSum += temp[i][i];
diagonalTwoSum += temp[diagonalTwoCounter][diagonalTwoCounter];
diagonalTwoCounter--;
}
if(diagonalOneSum!=magicNumber||diagonalTwoSum!=magicNumber){
isMagic = false;
return isMagic;
}
// check if there are repeated numbers in the pretty magic square already.
return noRepeatedNum(temp);
}
/**
*
* Function: check if the position of the number in the magic square is at boundary</br>
* #param boundary the row OR column number of the position
* #return true if the value of<code>boundary</code> is zero</br>
* Preston Jul 5, 20151:53:24 PM</br>
*/
private boolean Boundary(int boundary){
return boundary==0;
}
/**
*
* Function: Put numbers from 1 to n*n into my own 2D array using Siamese Method.</br>
* Preston Jul 5, 20153:20:56 PM</br>
*/
private void createMagicSquare(){
// starting Row number -> middle
int startRow = this.n/2;
// starting Column number -> the first column
int startColumn = 0;
// start to put number from 2
int startNum = 2;
// put 1 in the starting position
myMagicSquare[startRow][startColumn] = 1;
while(startNum<=n*n){
// the positions on upper boundary
if(Boundary(startRow)&&!Boundary(startColumn)){
myMagicSquare[n-1][startColumn-1] = startNum;
startRow = n-1;
startColumn -= 1;
}
// the positions on left boundary
else if(Boundary(startColumn)&&!Boundary(startRow)){
myMagicSquare[startRow-1][n-1] = startNum;
startRow -= 1;
startColumn = n-1;
}
// upper left corner.
else if(Boundary(startRow)&&Boundary(startColumn)){
myMagicSquare[startRow][startColumn+1] = startNum;
startColumn += 1;
}
else{
// if the coming position is filled with number.
if(myMagicSquare[startRow-1][startColumn-1]!=0){
myMagicSquare[startRow][startColumn+1] = startNum;
startColumn += 1;
}
// general movement
else{
myMagicSquare[startRow-1][startColumn-1] = startNum;
startRow -= 1;
startColumn -= 1;
}
}
startNum++;
}
}
public String toString() {
// align my 2D array.
return toString(myMagicSquare);
}
/**
*
* Function:align the numbers in the parameter 2D array pretty</br>
* #param temp the parameter 2D array.
* #return the beautifully aligned String</br>
* Preston Jul 5, 20153:26:15 PM</br>
*/
public static String toString(int[][] temp){
int largestNum = 0;
// get the largest number in temp.
for(int[] x : temp){
for(int a : x){
if(a>=largestNum)
largestNum = a;
}
}
// how many digits does the biggest number have?
int longestDigit = String.valueOf(largestNum*largestNum).length();
// store the final String
StringBuilder printOut = new StringBuilder();
printOut.append('\n');
for(int[] x : temp){
for(int a : x){
// space between each number
printOut.append('\t');
// add spaces for alignment.
for(int i=0;i<longestDigit-String.valueOf(a).length();i++){
printOut.append(" ");
}
printOut.append(String.valueOf(a));
}
printOut.append('\n').append('\n');
}
// return the big String
return printOut.toString();
}
/**
*
* Function: the main function scans user input as the length of 2D array to make my
* own magic square. If the <code>userInput</code> is out of range, print out the error
* message and ask for the number again. Enter the code 0 to exit.</br>
* #param args</br>
* Preston Jul 5, 20153:28:57 PM</br>
*/
public static void main(String[] args) {
int userInput;
do{
// title
System.out.println("Enter a positive, odd number");
System.out.print("Exit code is 0, enter 0 to quit: ");
// user input
userInput = new Scanner(System.in).nextInt();
// if the userInput is out of range, show error message.
if(rangeCheck(userInput)){
MagicSquare m = new MagicSquare(userInput);
System.out.println(m.toString());
}else
if(userInput==0)
System.out.println("The magic square is not generated. QUIT");
else
System.err.println("Wrong number: Please enter a positive, odd number");
// restart
System.out.println("-------------------");
}while(userInput != 0); // enter 0 to exit.
}
}
The reason for above issue is that bug in handling of stdout and stderr in eclipse.Follow this link. (Not sure whether this is fixed or not.)
I also tried to reproduce this issue, but it is occurring in some cases and in some cases output and error output is showing at correct places.
Just for check :-
You may get this issue at very first run on eclipse, so don't exit the code, try again with wrong number (i.e. 2/4/6 ...) ;you may see error and output gets correctly printed.

Need to work on an array recursively, trouble passing data, java

Ok, I am having a really beginner mistake here, but I can't think of what I need to do. I have an array permArray that I am recursively filling with possible permutations. I have a public method that gets the parameters ready, then I work on the array in the private method that calls itself to work on smaller and smaller parts.
The problem I am having, is how do I pass the finished array back to the public method. Would I return the array every time I am finished with the recursion (after I have placed the last element in each section, where the section size is 1).
Oh, and also, this is practice, not homework.
//todo:
//need to determine what is wrong with my array of linked lists
package wordchains;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
import java.util.StringTokenizer;
import javax.xml.soap.Node;
/**
*
* #author Samuel French
*/
public class WordChains {
public static void main(String[] args) {
//variables
int numWords = -1; //This will hold the number of words the user is inputting
String userInput; //holds the user input to be broken up into a string array
//Get the user's input, 0 is the quit value
Scanner sc = new Scanner(System.in);
System.out.print("Enter number of words: ");
numWords = sc.nextInt();
System.out.println(">");
sc.nextLine();
userInput = sc.nextLine();
String[] inputWords = userInput.split("\\s+");
int numElements = inputWords.length;
int numOfPerms = numOfPerms(numElements);
//We will start by checking the last letter of the first word
char cTest;
int wordChecking = 0;
int[][] permArray = genPerms(numElements, numOfPerms);
for (int col = 0; col < numOfPerms; col++) {
System.out.println();
for (int row = 0; row < numElements; row++) {
System.out.print(permArray[col][row] + " ");
}
}
}
public static int numOfPerms(int numElements) {
int numOfPerms = numElements;
numElements--;
while (numElements > 0) {
numOfPerms = numOfPerms * numElements;
System.out.println(numOfPerms);
numElements--;
}
return numOfPerms;
}
public static int[][] genPerms(int numElements, int totPerms) {
int permArray[][] = new int[totPerms][numElements];
//either do it like this or create an array of head nodes
List<LinkedList<Integer>> elementsLeftList = new ArrayList<LinkedList<Integer>>();
LinkedList tempList = new LinkedList();
for (int x = 0; x < numElements; x++) {
tempList.addLast(x);
}
for (int x = 0; x < totPerms; x++) {
elementsLeftList.add((LinkedList<Integer>) tempList.clone());
}
return privateGenPerms(permArray,elementsLeftList,totPerms,0,0,totPerms);
}
private static void privateGenPerms(int[][] permArray, List<LinkedList<Integer>> elementsLeftList, int totalPermutations, int elementPlacing, int sectionBegin, int sectionSize) {
//variables-
//totalPermutations - the total number of permutations in the whole problem
//elementPlacing - the element currently being placed's position, corresponds to the rows of permArray
//elementPlacingIndex - the number of times the element currently being placed has been placed
//sectionSize - the size of the total working section. First time this is the # of permutations
//permCounter - this counter counts the permutation working with within the section
//sectionBegin - counts the beginning of the section working with
//2 Data structures:
//permArray - 2d the array of permutations
//elementsLeftList - list of lists of elements left, corresponds to each permutation
int totalNumberOfElements = permArray[0].length;
//
int numberOfElementsLeftToPlace = totalNumberOfElements - elementPlacing;
//
int permCounter = sectionBegin;
//Base case
if (numberOfElementsLeftToPlace == 1) {
for (int x = 0; x < totalPermutations; x++) {
permArray[x][totalNumberOfElements - 1] = (int) elementsLeftList.get(permCounter).remove(0); //may need to be a remove 1, not sure
}
return; //need to decide what I am going to do here
}
//
int elementPlacingIndex = 0;
int elementCurrentlyPlacing = 0; //could be a 1, don't remember
//
int numberOfTimesToPlaceWithinCol = (sectionSize / numberOfElementsLeftToPlace);
//
//
for (; permCounter < (sectionBegin + sectionSize); permCounter++) {
//when we need to switch to a different partition of the section
if (elementPlacingIndex == numberOfTimesToPlaceWithinCol) {
elementPlacingIndex = 0;
elementCurrentlyPlacing++;
}
permArray[permCounter][elementPlacing] = (int) elementsLeftList.get(permCounter).remove(elementCurrentlyPlacing);
elementPlacingIndex++;
}
for (int newSectionBegin = sectionBegin; newSectionBegin < (sectionBegin + sectionSize); newSectionBegin = newSectionBegin + numberOfTimesToPlaceWithinCol) {
privateGenPerms(permArray, elementsLeftList, totalPermutations, (elementPlacing + 1), newSectionBegin, (sectionSize / numberOfElementsLeftToPlace));
}
}
}
The array is passed-by-reference, so any changes you make in the private function will be permanent and you do not need to return the modified array again.
I have not looked at your logic to see if this is the correct way to do it in your case though.

Categories