2D array null pointer exception - java

Okay, first off I can guarantee this has been asked, but I haven't found my specific problem and I don't have the rep to comment on an existing post. Basically I've instantiated a 2D array as a class object, since I need to access the array in multiple methods and changes have to stay permanent. However I don't know the actual needed size needed to create the matrix, and am getting null pointer exceptions when I try to change the size later.
Basically:
public static void sort(ArrayList<Character> line, int row)
{
System.out.println("line size " + (line.size()-1));
System.out.println("maze row check " + (maze[row] == null));
maze[row] = new int[line.size()-1];
for (int x = 0; x <line.size(); x++)
{
maze[row][x] = line.get(x);
System.out.println("final sopt " + maze[row][x]);
}
}
Is there a way to successfully do this? Or am I overlooking something very simple?
Thank you for taking the time to read / answer this,
Mark
And after what must be 10 edits going in circles here is the full code (full of printlns from testing and other code i just commented out because I didn't need it or wrote something better:
package maze;
import java.io.*;
import java.util.ArrayList;
import static java.lang.System.*;
public class Maze
{
private static int[][] maze;
public Maze(int size, String line)
{
}
public boolean hasExitPath(int r, int c)
{
return false;
}
public String toString()
{
String output="";
return output;
}
public static void doMaze(int x, int y)
{
}
public static void readMaze() throws IOException
{
System.out.println(0);
BufferedReader read = new BufferedReader(new FileReader("maze.dat"));
String numString;
int numLine;
String mazeLine;
int row = 0;
int x = 0;
int lastChar = 0;
while ((numString = read.readLine()) !=null && (mazeLine = read.readLine()) !=null)
{
System.out.println(1);
numLine = Integer.parseInt(numString.replaceAll("\\s+", ""));
System.out.println("numString" + numString + "numLine" + numLine); //both set to 5...
ArrayList<Character> curLine = new ArrayList<Character>();
for(int d = 0; d < numLine; d++) curLine.add('a');
System.out.println("curLine " + curLine.size());
for (int z = 0; z < mazeLine.length(); z++)
{
System.out.println(2);
// get first row of numbers >> need to check lastchar
// sort and send to get added
// if remainder of line is more than numLine
// go to step one, but start from lastchar
if (lastChar < curLine.size())
{
System.out.println(3);
for (x = 0; x < numLine; x++);
{
System.out.println(4);
curLine.add(mazeLine.charAt(x + lastChar));
}
lastChar = x + lastChar;
System.out.println("row " + row);
sort(curLine, row);
row++;
}
else{System.out.println("error"); System.out.println(lastChar); System.out.println(curLine.size());}
}
/*
numLine = Integer.parseInt(numString.replaceAll("\\s+", ""));
ArrayList<Character> curLine = new ArrayList<Character>(numLine);
for (int x = 0; x < numLine; x++)
{
//System.out.println(mazeLine.charAt(x));
System.out.println(maze[0][0]);
curLine.add(mazeLine.charAt(x));
}
y++; */
}
read.close();
}
public static void sort(ArrayList<Character> line, int row)
{
System.out.println("line size " + (line.size()-1));
System.out.println("maze row check " + (maze[row] == null));
maze[row] = new int[line.size()-1];
for (int x = 0; x <line.size(); x++)
{
maze[row][x] = Integer.parseInt(String.valueOf(line.get(x)));
System.out.println("final sopt " + maze[row][x]);
}
}
}

Related

How do I get rid of java.lang.NumberFormatException error

This code takes two txt files, reads them puts them in 2d arrays and should check if the numbers in the files are magic squares but it keeps returning NumberFormatException error. I'm new to java so if anyone could help me that would be great. I'm pretty sure the problem come from the txt file being string and the 2d array needing to be in int form. But how and where do I make that conversion on my code?
this is what i have:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.Scanner;
public class ms {
public static void main(String[] args) throws FileNotFoundException {
String filename1 = "magicSquaresData.txt", filename2 = "magicSquaresData.txt";
int nos[][] = null;
nos = getArray(filename1);
boolean b = isMagicSquare(nos);
printArray(nos);
if (b) {
System.out.println("It is a magic Square");
} else {
System.out.println("It is not a magic Square");
}
System.out.println("\n");
nos = getArray(filename2);
b = isMagicSquare(nos);
printArray(nos);
if (b) {
System.out.println("It is a magic Square");
} else {
System.out.println("It is not a magic Square");
}
}
private static int[][] getArray(String filename) throws FileNotFoundException {
String line;
int nos[][] = null;
int size = 0, rows = 0;
Scanner sc = null;
try {
sc = new Scanner(new File(filename));
while (sc.hasNext()) {
if (!sc.nextLine().isEmpty())
size++;
}
sc.close();
nos = new int[size][size];
sc = new Scanner(new File(filename));
while (sc.hasNext()) {
line = sc.nextLine();
if (!line.isEmpty()) {
String arr[] = line.split("\t");
for (int i = 0; i < arr.length; i++) {
nos[rows][i] = Integer.valueOf(arr[i]);
}
rows++;
}
}
sc.close();
} catch (FileNotFoundException e) {
System.out.println(e);
}
return nos;
}
private static void printArray(int[][] nos){
for(int i = 0; i<nos[0].length;i++) {
for (int j = 0; j < nos[0].length; j++){
System.out.printf("%-3d",nos[i][j]);
}
System.out.println();
}
}
private static boolean isMagicSquare(int[][] square) {
boolean bool = true;
int order = square.length;
int[] sumRow = new int[order];
int[] sumCol = new int[order];
int[] sumDiag = new int[2];
Arrays.fill(sumRow, 0);
Arrays.fill(sumCol, 0);
Arrays.fill(sumDiag, 0);
for (int row = 0; row < order; row++){
for (int col = 0; col < order; col++) {
sumRow[row] += square[row][col];
}
}
for (int col = 0; col < order; col++) {
for (int row = 0; row < order; row++) {
sumCol[col] += square[row][col];
}
}
for (int row = 0; row < order; row++) {
sumDiag[0] += square[row][row];
}
for (int row = 0; row < order; row++) {
sumDiag[1] += square[row][order - 1 - row];
}
bool = true;
int sum = sumRow[0];
for (int i = 1; i < order; i++) {
bool = bool && (sum == sumRow[i]);
}
for (int i = 0; i < order; i++) {
bool = bool && (sum == sumCol[i]);
}
for (int i = 0; i < 2; i++) {
bool = bool && (sum == sumDiag[i]);
}
return bool;
}
}
SUGGESTION:
Substitute nos[rows][i] = Integer.valueOf(arr[i]); for a custom method that will tell you WHERE the error is occurring.
EXAMPLE:
public static Integer tryParse(String text, int row, int i) {
try {
return Integer.parseInt(text);
} catch (NumberFormatException e) {
System.out.println("ERROR: row=" + row + ", i=" + i + ", text=" + text);
return null;
}
}
CAVEAT: This is for helping you troubleshoot ONLY. You definitely wouldn't want to release this in "production code" ;)
What is the NumberFormatException?
Thrown to indicate that the application has attempted to convert a string to one of the numeric types, but that the string does not have the appropriate format.
Offtopic:
A thing that i can notice is that both filesnames have the same name. So you will verify the same file 2 times.
String filename1 = "magicSquaresData.txt", filename2 = "magicSquaresData.txt";
I checked your program and you error appears when you put like this on a file:
1. 5 5
2. 5 5
So the error shows beacause you are trying to parse to int the String "5 5". So your code pick the all line and tries to convert to int and " " it's not an int. And there lives the NumberFormatException error.
How do to solve it?
The function that we will work on is the one that you pass from file to an array in
private static int[][] getArray(String filename) throws FileNotFoundException{
The of the function is after we read the file.
As you said, you are leading with a 2d array so to insert all the numbers we need to have loops for each dimension on the array.
So we will start from there.
I will use a while beacause we are dealing with a string and it's easier to verify the text that its left on the line. Will add a new int variable that starts in 0 to pass in every column of a line to use with the while loop. And with this we got this:
for (int i = 0; i < lines.length; i++) {
while(!"".equals(line)){
whileIterator++;
}
whileIterator = 0;
}
Next setep, we will divide in 2 behaviors because we will substring the String that has in the line, and will work differently when it's the last number that we are verifying:
for (int i = 0; i < lines.length; i++) {
while(!"".equals(line)){
if(whileIterator + 1 == size){//If its the last iteration that we need in a line
}else{//All other iterations
whileIterator++;
}
whileIterator = 0;}
To finalize let's add the new logic to insert in nos array. So lets pick all line for example 2 7 6 and we want to add the number 2, so lets do that. You just need to substring(int startIndex, int finalIndex) the line and add to the nos array. After that let remove the number and the space ("2 ") from the line that we are veryfying.
for (int i = 0; i < lines.length; i++) {
while(!"".equals(line)){
if(whileIterator + 1 == size){//If its the last iteration that we need
nos[rows][whileIterator] = Integer.parseInt(line.substring(0));//Add to array
line = "";//To not pass the while verification
}else{//All other iterations
nos[rows][whileIterator] = Integer.parseInt(line.substring(0, line.indexOf(" ")));//Add to array
line = line.substring(line.indexOf(" ") + 1);//remove the number we added behind
}
whileIterator++;
}
whileIterator = 0;}
And here you go, that how you add the numbers to an array and don't get the error.
If you need some further explanation just ask. Hope it helps :)

Java: My 2D array runs out of bounds 1 number less than it should every single time

I'm trying to add a string to a 2d array, maze. It compiles, but when I run it it gives "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3" even though the dimensionY is set to 4.
public static void main(String[] args) throws IOException
{
List<String> lines = Files.readAllLines(Paths.get("C:\\Users\\zarga\\OneDrive\\Documents\\HW\\CSIS139\\MazeSolver\\src\\maze.txt"));
// now print out what the text file has in a for loop.
for (String line : lines)
{
System.out.println(line);
}
String line = lines.toString();
System.out.println();
System.out.println("Dimensions: " + Dimensions1(lines) + " by " + Dimensions2(lines));
System.out.println("Start position y: " + getEndCoordinateY(line));
System.out.println("Start position x: " + getEndCoordinateX(line));
char[][] mazeArray = new char[Dimensions1(lines)][Dimensions2(lines)];
mazeArray = mazeCreator(lines, mazeArray );
}
//get first number in dimension
public static int Dimensions1(List<String> list)
{
String firstLine = "";
String stringList = list.toString();
for (int i = 1; i <= 3; i++)
{
firstLine = firstLine + stringList.charAt(i);
}
int firstDim = Integer.parseInt(firstLine);
return firstDim;
}
//get second number in the dimension
public static int Dimensions2(List<String> list)
{
String firstLine = "";
String stringList = list.toString();
for (int i = 5; i <= 7; i++)
{
firstLine = firstLine + stringList.charAt(i);
}
int secondDim = Integer.parseInt(firstLine);
return secondDim;
}
//get ending coordinate Y position
public static int getEndCoordinateY (String list)
{
String lastLine = "";
String stringList = list;
int startY = 0;
int length = list.length();
for(int i = length - 2; i > (length - 5); i--)
{
lastLine = stringList.charAt(i) + lastLine;
}
startY = Integer.parseInt(lastLine);
return startY;
}
//get ending coordinate X position
public static int getEndCoordinateX (String list)
{
String lastLine = "";
String stringList = list;
int startX = 0;
int length = list.length();
for(int i = length - 6; i > (stringList.length() - 9); i--)
{
lastLine = stringList.charAt(i) + lastLine;
}
startX = Integer.parseInt(lastLine);
return startX;
}
//create the maze
public static char[][] mazeCreator (List<String> list, char maze[][])
{
int dimensionX = Dimensions1(list);
int dimensionY = Dimensions2(list);
String lines = "";
String stringList = list.toString();
for(int i = 8; i <= stringList.length() - 18; i++)
{
if(stringList.charAt(i) == ',' || stringList.charAt(i) == ' ')
{
//do nothing to get rid of all ,'s or spaces
}
else
{
lines = lines + stringList.charAt(i);
}
}
System.out.println(lines);
int offset = 0;
for(int x = 0; x < dimensionX; x++)
{
for(int y = 0; y < dimensionY; y++)
{
maze[x][y] = lines.charAt(offset++);
}
}
System.out.println(maze);
return maze;
}
}
I've printed Dimensions1(lines) and Dimensions2(lines) and both come out to 4. So the dimensions should be 4 by 4, but for some reason it runs out of bounds at 3.

Boolean troubles with WordSearch class

Im having difficulty changing my boolean to true, if the word is found.
import java.util.Scanner;
public class WordSearch
{
private char[][] array;
private boolean found;
public WordSearch(char[][] inArray)
{
array = inArray;
}
public void play()
{
Scanner in = new Scanner(System.in);
String choice = "";
while(!choice.equals("end"))
{
print();
System.out.println("What word do you want to search for? (Type end to quit)");
choice = in.nextLine();
System.out.println();
switch (choice)
{
case "end":
break;
default:
search(choice);
break;
}
}
}
public void print()
{
for(int i = 0; i < array.length; i++)
{
for(int j = 0; j < array[0].length; j++)
{
System.out.print(array[i][j]);
}
System.out.println();
}
System.out.println();
}
public void search(String inWord)
{
// Puts inWord into an array
char[] word = new char[inWord.length()];
for(int i = 0; i < inWord.length(); i++)
{
word[i] = inWord.charAt(i);
}
for(int i = 0; i < array.length; i++)// goes to each row
{
for(int j = 0; j < array[0].length; j++)// goes through every letter
{
if(array[i][j] == word[0])// asks if it matches
{
lookHorizantal(word, array, i, j, found);
lookVertical(word, array, i, j, found);
lookDiagnal(word, array, i, j, found);
}
}
}
if(!found)
{
System.out.println(inWord + "was not found!");
}
System.out.println();
}
public void lookHorizantal(char[] inWord, char[][] inArray, int row, int column, boolean ifFound)
{
int counter = 1; //set this to one because we already found the first letter
column += 1;
for(int i = 0; i < inWord.length; i++)
{
if(column < 15 && counter < inWord.length)
{
if(inArray[row][column] == inWord[counter])
{
//System.out.println("WE FOUND A LETTER AT COLUMN: " + row + " Row: " + column);
counter += 1;
column += 1;
}
}
}
if(counter == inWord.length)
{
ifFound = true;
System.out.println(printChar(inWord) + " found horizontally at row " + row + " and column " + (column - counter) + "!");
}
}
public void lookVertical(char[] inWord, char[][] inArray, int row, int column, boolean ifFound)
{
int counter = 1; //set this to one because we already found the first letter
row += 1;
for(int i = 0; i < inWord.length; i++)
{
if(row < 10 && counter < inWord.length)
{
if(inArray[row][column] == inWord[counter])
{
//System.out.println("WE FOUND A LETTER AT COLUMN: " + row + " Row: " + column);
counter += 1;
row += 1;
}
}
}
if(counter == inWord.length)
{
ifFound = true;
System.out.println(printChar(inWord) + " found vertically at row " + (row - counter) + " and column " + column + "!");
}
}
public void lookDiagnal(char[] inWord, char[][] inArray, int row, int column, boolean ifFound)
{
int counter = 1; //set this to one because we already found the first letter
row += 1;
column += 1;
for(int i = 0; i < inWord.length; i++)
{
if(row < 10 && column < 15 && counter < inWord.length)
{
if(inArray[row][column] == inWord[counter])
{
//System.out.println("WE FOUND A LETTER AT COLUMN: " + row + " Row: " + column);
counter += 1;
row += 1;
column +=1;
}
}
}
if(counter == inWord.length)
{
ifFound = true;
System.out.println(printChar(inWord) + " found diagnolly at row " + (row - counter) + " and column " + (column - counter) + "!");
}
}
public String printChar(char[] inChar)
{
String complete = "";
for(int i = 0; i < inChar.length; i++)
{
complete += inChar[i];
}
return complete;
}
}
Every time I find a word it returns false and runs the not found. Am I not declaring the boolean right? or is it resetting when it gets out of a method?
Heres the driver if you want to test it out:
import java.util.*;
import java.io.*;
public class Driver
{
public static void main (String[] args)
{
// try block needed to read in file
try
{
//open the file "sampleSearch.txt"
FileReader fileName = new FileReader("sampleSearch.txt");
Scanner fileRead = new Scanner(fileName);
//read in the number of rows
int numRow = fileRead.nextInt();
fileRead.nextLine();
//read in the number of columns
int numCol = fileRead.nextInt();
fileRead.nextLine();
//create a 2d array to hold the characters in the file
char[][] array = new char[numRow][numCol];
//for each row in the file
for (int r = 0; r < numRow; r++)
{
//read in the row as a string
String row = fileRead.nextLine();
//parse the string into a sequence of characters
for (int c = 0; c < numCol; c++)
{
//store each character in the 2d array
array[r][c] = row.charAt(c);
}
}
//create a new instance of the WordSearch class
WordSearch ws = new WordSearch(array);
//play the game
ws.play();
}
catch (FileNotFoundException exception)
{
//error is thrown if file cannot be found. See directions or email me...
System.out.println("File Not Found");
}
}
}
and heres sampleSearch.txt:
10
15
fqexfecmxdvjlgu
cxomfslieyitqtz
nucatfakuxofegk
hfytpnsdlhcorey
pgrhdqsypyscped
ckadhyudtioapje
yerjodxnqzztfmf
hypmmgoronkzhuo
hdskymmpkzokaao
amuewqvtmrlglad
You cannot modify your immutable primitive boolean (or even a Boolean wrapper) in a called method, changes to the reference will not be preserved outside of the method. Instead, you have two choices -
Store the state in an object field, and provide an accessor for that field (e.g. a getter),
Return boolean (or Boolean) from that method (instead of `void`).
When you pass found as an argument you are passing its value, and not a reference to it, so essentially you are creating a method instance variable.
I would suggest two options
The first would be to return the value:
found = lookHorizantal(word, array, i, j);
// Maybe check between these search calls if it is found?
found = lookVertical(word, array, i, j);
// Maybe check between these search calls
found = lookDiagnal(word, array, i, j);
// Maybe check between these search calls if it is found?
public boolean lookHorizantal(char[] inWord, char[][] inArray, int row, int column)
{
// OMITTED CODE
if(counter == inWord.length)
{
return true; /*******************/
// OMITTED CODE
}
}
or just reference the class variable:
public void lookHorizantal(char[] inWord, char[][] inArray, int row, int column)
{
// OMITTED CODE
if(counter == inWord.length)
{
found = true; /*******************/
// OMITTED CODE
}
}
These switches will change the class variable found directly.

Sorting Java Multidimensional Array

I'm trying to sort the contents of an array and while it seems to be working (no runtime errors; is performing sort tasks), the first 10 rows, while sorted, are not in order with the rest of the rows.
class coordSort.java
import java.io.*;
import java.util.Arrays;
import java.util.Scanner;
public class coordSort {
#SuppressWarnings({ "unchecked", "unused" })
public static void main (String args[]) throws IOException {
String xCoord, yCoord;
int coordSum;
Scanner input = new Scanner(System.in);
//Get x coordinate from user
System.out.print("Enter x coordinate: ");
xCoord = input.next();
//Get x coordinate from user
System.out.print("Enter y coordinate: ");
yCoord = input.next();
boolean sort = false;
char[] a = xCoord.toCharArray();
char[] b = yCoord.toCharArray();
//validate user input is a digit
if ( (Character.isDigit(a[0])) ) {
if(Character.isDigit(b[0]) ){
//digits entered - begin processing all coordinate values
sort = true;
}
}
//If validation failed, inform user
if(!sort){
System.out.println("Please enter a positive numeric value.");
}
if(sort){
//determine SUM of user entered coordinates
coordSum = Integer.parseInt(xCoord) + Integer.parseInt(yCoord);
//define coordinate array
String[][] coordUnsortedArray = new String[26][3];
int counter;
int commaCount;
String xCoordIn, yCoordIn;
int intXCoordIn, intYCoordIn, sumCoordIn, coordDiff;
//define input file
FileInputStream fileIn = new FileInputStream("coords.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(fileIn));
for (int j = 0; j < coordUnsortedArray.length; j++){
counter = 0;
commaCount = 0;
//line from file to variable
String coordSet = reader.readLine();
//look for the second "," to determine end of x coordinate
for(int k = 0; k < coordSet.length(); k++){
if (coordSet.charAt(k) == ',') {
commaCount++;
counter++;
if (commaCount == 2){
break;
}
}else{
counter++;
}
}
//define x coordinate
xCoordIn = (coordSet.substring(2,(counter - 1)));
intXCoordIn = Integer.parseInt(xCoordIn);
//define y coordinate
yCoordIn = (coordSet.substring((counter),coordSet.length()));
intYCoordIn = Integer.parseInt(yCoordIn);
//coordinate calculations
sumCoordIn = Integer.parseInt(xCoordIn) + Integer.parseInt(yCoordIn);
coordDiff = sumCoordIn - coordSum;
//load results to array
coordUnsortedArray[j][0] = xCoordIn;
coordUnsortedArray[j][1] = yCoordIn;
coordUnsortedArray[j][2] = Integer.toString(coordDiff);
//Output Array (BEFORE SORTING)
//System.out.println((j + 1) + ") " + coordUnsortedArray[j][0] + " : " + coordUnsortedArray[j][1] + " : " + coordUnsortedArray[j][2]);
}
System.out.println("\n");
fileIn.close();
String[][] coordsSorted = new String[26][3];
//Sort array coordDiff, column 3
Arrays.sort(coordUnsortedArray, new ColumnComparator(2));
//Print the sorted array
for(int i = 0; i < coordUnsortedArray.length; i++){
String[] row = coordUnsortedArray[i];
System.out.print((i + 1) + ") ");
for(int j = 0; j < row.length; j++) {
//System.out.print(row[j] + " | ");
coordsSorted[i][j] = row[j];
System.out.print(coordsSorted[i][j] + " : ");
}
System.out.print("\n");
}
}
}
}
class sortCoords.java --
import java.util.Comparator;
#SuppressWarnings("rawtypes")
class ColumnComparator implements Comparator {
int columnToSort;
ColumnComparator(int columnToSort) {
this.columnToSort = columnToSort;
}
//overriding compare method
public int compare(Object o1, Object o2) {
String[] row1 = (String[]) o1;
String[] row2 = (String[]) o2;
//compare the columns to sort
return row1[columnToSort].compareTo(row2[columnToSort]);
}
//overriding compare method
public int compare1(Object o1, Object o2) {
String[] row1 = (String[]) o1;
String[] row2 = (String[]) o2;
//compare the columns to sort
return row1[columnToSort].compareTo(row2[columnToSort]);
}
}
I am trying to sort the array in numerical order by the 3rd column. The unsorted array is populated by a text file containing something like:
a,44,67
b,31,49
c,93,6
I am performing calculations on the array compared to user input and populating the array as follows:
44,67,101
31,49,70
93,6,89
I would like the sortedArray to output the following:
31,49,70
93,6,89
44,67,101
One possible confusion here:
return row1[columnToSort].compareTo(row2[columnToSort])
This is a string comparison, not a numerical one. If you sort based on strings, you will get different results than if you do by numbers - ie "1","10","100","9" vs 1,9,10,100
Check out Integer.parseInt and if you can't figure out the rest, feel free to ask more questions.
As spinning_plate stated. You need to compare their int values i.e. you need a cast there
int num1 = Integer.parseInt(row1[columnToSort]);
int num2 = Integer.parseInt(row2[columnToSort]);
if(num1 > num2)
return 1;
else
return 0;
Place this code in the compareTo method and check. Swap the return statements to sort in reverse order.
Also, adding some error checking in the compareTo method will make the code more efficient.
Ok, so after the assistance provided here, below is the solution that we found. Thanks again for the help everyone! Hopefully the code below helps someone else out.
Code for class1 --
import java.io.*;
import java.util.Arrays;
import java.util.Scanner;
public class coordSort {
#SuppressWarnings({ "unchecked" })
public static void main (String args[]) throws IOException {
String xCoordChar, yCoordChar;
int xCoord, yCoord, coordSum;
Scanner input = new Scanner(System.in);
//Get x coordinate from user
System.out.print("Enter x coordinate: ");
xCoordChar = input.next();
//Get x coordinate from user
System.out.print("Enter y coordinate: ");
yCoordChar = input.next();
boolean sort = false;
char[] a = xCoordChar.toCharArray();
char[] b = yCoordChar.toCharArray();
//validate user input is a digit
if ( (Character.isDigit(a[0])) ) {
if(Character.isDigit(b[0]) ){
//digits entered - begin processing all coordinate values
sort = true;
}
}
//If validation failed, inform user
if(!sort){
System.out.println("Please enter a positive numeric value.");
}
if(sort){
//Parse user input characters to Integers
xCoord = Integer.parseInt(xCoordChar);
yCoord = Integer.parseInt(yCoordChar);
//determine SUM of user entered coordinates
coordSum = xCoord + yCoord;
//define coordinate array
int[][] coordUnsortedArray = new int[26][3];
int counter;
int commaCount;
String xCoordIn, yCoordIn;
int intXCoordIn, intYCoordIn, sumCoordIn, coordDiff;
//define input file
FileInputStream fileIn = new FileInputStream("coords.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader (fileIn));
for (int j = 0; j < coordUnsortedArray.length; j++){
counter = 0;
commaCount = 0;
//line from file to variable
String coordSet = reader.readLine();
//look for the second "," to determine end of x coordinate
for(int k = 0; k < coordSet.length(); k++){
if (coordSet.charAt(k) == ',') {
commaCount++;
counter++;
if (commaCount == 2){
break;
}
}else{
counter++;
}
}
//define x coordinate
xCoordIn = (coordSet.substring(2,(counter - 1)));
intXCoordIn = Integer.parseInt(xCoordIn);
//define y coordinate
yCoordIn = (coordSet.substring((counter),coordSet.length()));
intYCoordIn = Integer.parseInt(yCoordIn);
//coordinate calculations
sumCoordIn = Integer.parseInt(xCoordIn) + Integer.parseInt (yCoordIn);
coordDiff = sumCoordIn - coordSum;
if (coordDiff < 0){
coordDiff = coordDiff * (-1);
}
//load results to array
coordUnsortedArray[j][0] = intXCoordIn;
coordUnsortedArray[j][1] = intYCoordIn;
coordUnsortedArray[j][2] = coordDiff;
}
fileIn.close();
System.out.print("\n");
System.out.println("Array Before Sorting:");
System.out.println("=====================");
//Array Before Sorting
for(int i = 0; i < coordUnsortedArray.length; i++){
int[] row = coordUnsortedArray[i];
System.out.print((i + 1) + ") ");
for(int j = 0; j < (row.length - 1); j++) {
coordUnsortedArray[i][j] = row[j];
if(j < 1){
System.out.print(coordUnsortedArray [i] [j] + ",");
}else{
System.out.println(coordUnsortedArray [i] [j]);
}
}
}
System.out.print("\n");
System.out.print("\n");
//Sort array coordDiff, column 3
Arrays.sort(coordUnsortedArray, new ColumnComparator(2));
System.out.println("Array After Sorting:");
System.out.println("====================");
//Original Array After Sorting
for(int i = 0; i < coordUnsortedArray.length; i++){
int[] row = coordUnsortedArray[i];
System.out.print((i + 1) + ") ");
for(int j = 0; j < (row.length - 1); j++) {
coordUnsortedArray[i][j] = row[j];
if(j < 1){
System.out.print(coordUnsortedArray[i][j] + ",");
}else{
System.out.println(coordUnsortedArray [i] [j]);
}
}
}
}
}
}
Code for class2 --
import java.util.Comparator;
#SuppressWarnings("rawtypes")
class ColumnComparator implements Comparator {
int columnToSort;
ColumnComparator(int columnToSort) {
this.columnToSort = columnToSort;
}
//Compare method
public int compare(Object o1, Object o2) {
int[] row1 = (int[]) o1;
int[] row2 = (int[]) o2;
int intRow1 = (row1[columnToSort]);
int intRow2 = (row2[columnToSort]);
return new Integer(intRow1).compareTo(new Integer(intRow2));
}
}

UVa 630 kept getting wrong answer [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 11 years ago.
I have been working on the UVa 630 problem for 2 days, http://acm.uva.es/p/v6/630.html
I have written a working code, however constantly getting the wrong answer result after the submission, my program works fine for the given input format and generate correct result, could someone please take a look at my code and find what's wrong with it please.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Iterator;
class Main {
String[] init;
String[] sorted;
int voca = 0;
String[] test;
private String x;
private String y;
ArrayList<ArrayList> initial = new ArrayList<ArrayList>();
char[] charArray;
String input;
void initSort(String i) {
input = i;
charArray = input.toCharArray();
}
char[] get() {
return charArray;
}
void sort(int low, int high) {
int i = low;
char pivot = charArray[low];
for (int j = low + 1; j < high; j++) {
if (charArray[j] < pivot) {
if (j > i + 1) {
exchange(i + 1, j);
}
i++;
}
}
exchange(low, i);
if (i > low + 1)
sort(low, i);
if (i + 2 < high)
sort(i + 1, high);
}
void exchange(int i, int j) {
char temp = charArray[i];
charArray[i] = charArray[j];
charArray[j] = temp;
}
// ********************************************
void begin() {
// System.out.println("begin test");
int numOfdataSet;
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
try {
numOfdataSet = Integer.parseInt(in.readLine());
do {
ArrayList currentSet = new ArrayList();
int numberOfdic;
String tempStringV;
String tempStringT;
int i = 0;
try {
String emptyLine = in.readLine();
numberOfdic = Integer.parseInt(in.readLine());
;
currentSet.add(emptyLine);
currentSet.add(Integer.toString(numberOfdic));
// System.out.println("enter numberOfdic is " +
// numberOfdic);
while (i < numberOfdic) {
tempStringV = in.readLine();
currentSet.add(tempStringV);
i++;
}
// System.out.println("input test word");
tempStringT = in.readLine();
currentSet.add(tempStringT);
while (!tempStringT.equals("END")) {
tempStringT = in.readLine();
currentSet.add(tempStringT);
}
} catch (IOException e) {
e.printStackTrace();
}
initial.add(currentSet);
numOfdataSet--;
} while (numOfdataSet != 0);
} catch (IOException e) {
}
;
print();
}
// ***************************************************
void getArrays(ArrayList<String> a) {
// read the file and put the words into a temporary array
String[] temp = new String[a.size()];
for (int i = 0; i < a.size(); i++) {
temp[i] = a.get(i);
// System.out.println("temp "+i+" is "+temp[i]);
}
// extract the vocabulary counter from the temp array
int vocaCounter;
int shift;
if (!temp[0].equals("")) {
shift = 2;
vocaCounter = Integer.parseInt(temp[1]);
} else {
shift = 2;
vocaCounter = Integer.parseInt(temp[1]);
}
// System.out.println("there are "+vocaCounter);
// store the vocabulary into the array named as init
init = new String[vocaCounter];
for (int i = shift; i < vocaCounter + shift; i++) {
init[i - shift] = temp[i];
// System.out.println(i - shift + " voca is " + init[i - shift]);
}
// store the test words into the array named as test
test = new String[temp.length - vocaCounter - shift - 1];
for (int j = 0; j < temp.length - vocaCounter - shift - 1; j++) {
test[j] = temp[j + vocaCounter + shift];
// System.out.println("test "+j+" is "+test[j]);
}
sorted = init;
}
/**
* sort the two strings
*/
void arraySorter() {
x = x.toLowerCase();
initSort(x);
sort(0, x.length());
get();
// java.util.Arrays.sort(FirstArray);
y = y.toLowerCase();
initSort(y);
sort(0, y.length());
get();
}
String getEle(String in) {
initSort(in);
sort(0, in.length());
return new String(get());
}
void print() {
Iterator<ArrayList> iterator = initial.iterator();
while (iterator.hasNext()) {
getArrays((ArrayList<String>) iterator.next());
// ****************
/**
* sort the test array and store it as the testSort array
*/
String[] testSort = new String[test.length];
for (int i = 0; i < test.length; i++) {
testSort[i] = test[i];
}
for (int i = 0; i < test.length; i++) {
testSort[i] = getEle(testSort[i]);
}
// for(int i=0;i<test.length;i++)
// {
// System.out.println("test is "+test[i]+" and test sorted is "+testSort[i]);
// }
/**
* sort the vocabulary array and store the sorted array as vocaSort
*/
String[] vocaSort = new String[init.length];
for (int i = 0; i < init.length; i++) {
vocaSort[i] = init[i];
}
for (int i = 0; i < init.length; i++) {
vocaSort[i] = getEle(vocaSort[i]);
}
// start the testing process
for (int i = 0; i < test.length; i++) {
int counter = 1;
System.out.println("Anagrams for: " + test[i]);
for (int j = 0; j < sorted.length; j++) {
// anagramTester(test[i], init[j]);
boolean result = testSort[i].equals(vocaSort[j]);// //AnagramTester();
if (result == true && counter < 10) {
System.out.println(" " + counter + ") " + init[j]);
counter++;
} else if (result == true && counter < 100) {
System.out.println(" " + counter + ") " + init[j]);
counter++;
} else if (result == true && counter < 1000) {
System.out.println("" + counter + ") " + init[j]);
counter++;
}
}
if (counter == 1)
System.out.println("No anagrams for: " + test[i]);
}
System.out.println();
}
}
/**
* main function
*
* #param args
*/
public static void main(String[] args) {
Main myWork = new Main(); // create a dinamic instance
myWork.begin();
}
}
below is the input.txt file
1
4
atol
lato
rola
tara
kola
tola
END
2
24
uhgj
uhjg
ughj
ugjh
ujhg
ujgh
hujg
hugj
hgju
hguj
hjgu
hjug
guhj
gujh
ghuj
ghju
gjuh
gjhu
jugh
juhg
jhgu
jhug
jghu
jguh
jguh
END
it was a output format issue and problem solved

Categories

Resources