Why is there StringOutofBoundException? - java

My code needs to read information from the textfile. And the textfile looks like this:
X...................
....................
....................
....................
....................
....................
....................
....................
....................
..X.................
Yes, I need to get # of rows and columns and also identify the number and location of 'X's. I'm almost done except my second constructor is giving me a StringOutOfBoundException in the line:
treasureLocations[location] = new Coord(i, j);
I need help only with the second constructor. Could smb please help me with that?
import java.util.Scanner; // Required to get input
import java.io.File; // Required to get input from files
// A 2D treasure map which stores locations of treasures in an array
// of coordinates
public class TreasureMap{
int rows, cols; // How big is the treasure map
Coord [] treasureLocations; // The locations of treasures
Scanner kbd = new Scanner(System.in);
// Prompt the user for info on the treasure map and then create it
// COMPLETE THIS METHOD
public TreasureMap(){
int numberOfTreasures = 0;
System.out.println("Enter map size (2 ints): ");
rows = kbd.nextInt(); cols = kbd.nextInt();
System.out.println("Enter number of treasures (1 int): ");
numberOfTreasures = kbd.nextInt();
treasureLocations = new Coord[numberOfTreasures];
for (int i = 0; i < numberOfTreasures; i++)
{
System.out.println("Enter treasure " + i + " location (2 ints): ");
rows = kbd.nextInt(); cols = kbd.nextInt();
treasureLocations[i] = new Coord(rows, cols);
}
}
// Read the string representation of a map from a file
// COMPLETE THIS METHOD
public TreasureMap(String fileName) throws Exception{
rows = 0;
cols = 0;
int treasures = 0;
char x = 'X';
Scanner data = new Scanner(new File(fileName));
while(data.hasNextLine())
{
String line = data.nextLine();
for (int i = 0; i < line.length(); i++)
{
if(x == line.charAt(i))
{
treasures++;
}
}
cols = line.length();
rows++;
}
int location = 0;
treasureLocations = new Coord[treasures];
Scanner temp = new Scanner (new File(fileName));
while(temp.hasNextLine())
{
String line = temp.nextLine();
for(int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
if(x == line.charAt(j))
{
treasureLocations[location] = new Coord(i, j);
location++;
}
}
}
}
}
// true if there is treasure at the given (r,c) coordinates, false
// otherwise
// This method does not require modification
public boolean treasureAt(int r, int c){
for(int i=0; i<treasureLocations.length; i++){
Coord coord = treasureLocations[i];
if(coord.row == r && coord.col == c){
return true;
}
}
return false;
}
// Create a string representation of the treasure map
// This method does not require modification
public String toString(){
String [][] map = new String[this.rows][this.cols];
for(int i=0; i<rows; i++){
for(int j=0; j<cols; j++){
map[i][j] = ".";
}
}
for(int i=0; i<treasureLocations.length; i++){
Coord c = treasureLocations[i];
map[c.row][c.col] = "X";
}
StringBuilder sb = new StringBuilder();
for(int i=0; i<rows; i++){
for(int j=0; j<cols; j++){
sb.append(map[i][j]);
}
sb.append("\n");
}
return sb.toString();
}
}

You should not use the for i as you do. Your i means the current row, doesn't it? So every time you input a line(temp.nextLine()), your i must be added one.
int i=0;
while(temp.hasNextLine())
{
String line = temp.nextLine();
for (int j = 0; j < cols; j++)
{
if(x == line.charAt(j))
{
treasureLocations[location] = new Coord(i, j);
location++;
}
}
}
++i;
}

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 :)

Function is just reversing the order of the input instead of sorting it in descending order

I need to make a program that will take string inputs from user and store it in an array. I will then need to make a function that first: sorts each String {character by character} in descending order and second: will sort all String input in descending order {Strings}.
package com.company;
import java.util.Arrays;
import java.util.Scanner;
public class Main {
static String sortString(String str)
{
char[] chArr = str.toCharArray();
String SortString = "";
// For sorting each individual strings character by character
for (int i = 0; i< chArr.length; i++)
{
for (int j = 0; j < chArr.length; j++)
{
if(chArr[i] > chArr[j])
{
char temp = chArr[i];
chArr[i] = chArr[j];
chArr[j] = temp;
}
}
}
//converting all of the character into a single string
for (int k = 0; k<chArr.length;k++)
{
SortString = SortString + chArr[k];
}
//Assigning the current String Sortstring to an array
String[] OldArray = new String[5];
for (int counter = 0; counter<5; counter++)
{
OldArray[counter] = SortString;
}
//sorting all of the strings in descending order
for (int i = 0; i< OldArray.length;i++)
{
for (int j = i+1; j< OldArray.length;j++)
{
if(OldArray[i].compareTo(OldArray[j]) > 0)
{
String temp = OldArray[i];
OldArray[i] = OldArray[j];
OldArray[j] = temp;
}
}
}
return OldArray[0];
}
public static void main(String[] args)
{
Scanner UserInput = new Scanner (System.in);
String[] names = new String[5];
// will take a String user input from a user and store it in an arra
for (int counter = 0; counter<5; counter++)
{
do
{
System.out.print("Input String #" + (counter+1) + ": ") ;
names[counter] = UserInput.next().toLowerCase();
}while(names[counter].length() > 25);
}
//will print the assorted array
for(int i = 4; i >= 0; i--)
{
System.out.println((sortString(names[i])));
}
}
}
Input:
Input String #1: Stackoverflow
Input String #2: Java
Input String #3: ZZrot
Input String #4: coding
Input String #5: sorting
Output
tsronig
onigdc
zztro
vjaa
wvtsroolkfeca
Expected Output:
zztro
wvtsroolkfeca
vjaa
tsronig
onigdc
Sorry for the question I honestly don't know what to do
You're very close to the solution.
It's impossible to sort the array of strings in sortString because it only has access to the one string you pass in. Move the array sorting code to a separate method, and then you can call it while passing it the entire array:
static String sortString(String str) {
char[] chArr = str.toCharArray();
String SortString = "";
// For sorting each individual strings character by character
for (int i = 0; i < chArr.length; i++) {
for (int j = 0; j < chArr.length; j++) {
if (chArr[i] > chArr[j]) {
char temp = chArr[i];
chArr[i] = chArr[j];
chArr[j] = temp;
}
}
}
//converting all of the character into a single string
for (int k = 0; k < chArr.length; k++) {
SortString = SortString + chArr[k];
}
return SortString;
}
static void sortArray(String[] OldArray) {
//sorting all of the strings in descending order
for (int i = 0; i< OldArray.length;i++)
{
for (int j = i+1; j< OldArray.length;j++)
{
if(OldArray[i].compareTo(OldArray[j]) > 0)
{
String temp = OldArray[i];
OldArray[i] = OldArray[j];
OldArray[j] = temp;
}
}
}
}
The main method needs a small change too: the characters in the strings have to be sorted before you sort the array. Here, the characters are sorted while reading the input, and then the array is sorted with one call to sortArray:
public static void main(String[] args)
{
Scanner UserInput = new Scanner (System.in);
String[] names = new String[5];
// will take a String user input from a user and store it in an arra
for (int counter = 0; counter<5; counter++)
{
do
{
System.out.print("Input String #" + (counter+1) + ": ") ;
names[counter] = sortString(UserInput.next().toLowerCase());
}while(names[counter].length() > 25);
}
sortArray(names);
//will print the assorted array
for(int i = 4; i >= 0; i--)
{
System.out.println(names[i]);
}
}
Just made some changes to your code. sortString() was working fine.
Made only changes to main() method:
Got expected output, Try this:
public static void main(String[] args)
{
Scanner UserInput = new Scanner (System.in);
String[] names = new String[5];
// will take a String user input from a user and store it in an arra
for (int counter = 0; counter<5; counter++)
{
do
{
System.out.print("Input String #" + (counter+1) + ": ") ;
names[counter] = UserInput.next().toLowerCase();
}while(names[counter].length() > 25);
}
//will print the assorted array
String[] namesReversed = new String[names.length];
for(int i=0;i<names.length;i++){
namesReversed[i]=sortString(names[i]);
}
Arrays.sort(namesReversed, String::compareToIgnoreCase);
for(int i = namesReversed.length-1; i>=0; i--)
{
System.out.println(namesReversed[i]);
}
}

how to ranking of race time

I need to write a program that can ranking race time of 10 runners
so I created 2 arrays
ID of runners (10 runners)
race time of 10 runners (race time must be less than or equal to 20.0 sec)
and I found that my sorting algorithm can't be used correctly, I don't want to use Arrays.sort(x); because I need to sort "those race time and ID" here is my code
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String[] ID = new String[10];
double[] time = new double[10];
for (int i = 0; i < ID.length; i++) {
System.out.print("Please enter ID and times: ");
ID[i] = sc.nextLine();
time[i] = sc.nextDouble();
}
Run a = new Run(ID, time);
System.out.println("Top 3 is ");
a.Sort();
}
}
and
public class Run {
private String[] ID = new String[10];
private double[] time = new double[10];
public Run(String[] ID, double[] time) {
for (int i = 0; i < ID.length; i++) {
this.ID[i] = ID[i];
}
for (int i = 0; i < time.length; i++) {
if (time[i] <= 20.0) {
this.time[i] = time[i];
}
}
}
public void Sort() {
double tem1;
String tem2;
for (int i = 0; i < time.length; i++) {
for (int j = 0; j < time.length; j++) {
if (time[j] > time[j+1]) {
tem1 = time[j];
time[j] = time[j+1];
time[j+1] = tem1;
tem2 = ID[j];
ID[j] = ID[j+1];
ID[j+1] = tem2;
}
}
}
for (int i = 0; i < 3; i++) {
System.out.println(ID[i] + " " + time[i]);
}
}
}
so I need to know why my sorting algorithm can't be used correctly, it's pop an error on my console.
One more question, in the input stage when I input first ID and time, if I press like this
ID[0] -> Enter -> time[0]
then the input is correct but if I press
ID[0] -> Spacebar -> time[0]
then the input is wrong.
Why? And how do I fix it?
First thing I see is that you are passing an array of 10 elements in the constructor of Run; this is not necessary, you can directly pass the arrays:
In main:
Run a = new Run(ID, time);
In run:
public Run(String[] ID, double[] time) {
this.ID = ID;
this.time = time;
}
Can you post the error log?
Read here for the problem in reading the inputs: Read integers and strings from a single line of a console
The problem is that you are trying to get in an array cell that doesn't exist: array.length returns the length of the array, so in that case returns 10.
You are doing a for cycle from 0 to 10, then you are trying to get (in the if statement) inside time[11] (it was time[j+1]).
Change the for cycle to:
for (int i = 0; i < time.length - 1; i++) {
for (int j = 0; j < time.length - 1; j++) {
System.out.println(i + " "+ j);
if (time[j] > time[j+1]) {
tem1 = time[j];
time[j] = time[j+1];
time[j+1] = tem1;
tem2 = ID[j];
ID[j] = ID[j+1];
ID[j+1] = tem2;
}
}
}
#Pleasant94 answered your question regarding the index error.
To answer your question about why you need to enter a new line (press enter) after inputting the ID is because you are scanning the whole line into the ID value using nextLine(). Instead of using nextInt() like you did for time with nextDouble().
like so:
...
ID[i] = sc.nextInt();
time[i] = sc.nextDouble();
...
Check out the Java docs for the scanner class here: https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
And because you are now scanning in a int you'll have to update all your ID variables to int. Combining it with Pleasant94's answer you should be able to do just do this:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] ID = new int[10];
double[] time = new double[10];
for (int i = 0; i < ID.length; i++) {
System.out.print("Please enter ID and times: ");
ID[i] = sc.nextInt();
time[i] = sc.nextDouble();
}
Run a = new Run(ID, time);
System.out.println("Top 3 is ");
a.Sort();
}
}
class Run {
private int[] ID = new int[10];
private double[] time = new double[10];
public Run(int[] ID, double[] time) {
for (int i = 0; i < ID.length; i++) {
this.ID[i] = ID[i];
}
for (int i = 0; i < time.length; i++) {
if (time[i] <= 20.0) {
this.time[i] = time[i];
}
}
}
public void Sort() {
double tem1;
int tem2;
for (int i = 0; i < time.length - 1; i++) {
for (int j = 0; j < time.length - 1; j++) {
if (time[j] > time[j+1]) {
tem1 = time[j];
time[j] = time[j+1];
time[j+1] = tem1;
tem2 = ID[j];
ID[j] = ID[j+1];
ID[j+1] = tem2;
}
}
}
for (int i = 0; i < 3; i++) {
System.out.println(ID[i] + " " + time[i]);
}
}
}

How to copy a table to another table greater by 1

I cant use Lists, it must be in tables. How to copy a table to another table greater by 1? Im adding some elements to my table and if there is not enough space i want create new/copy table greater by 1.
Code:
Scanner sc = new Scanner(System.in);
String addNew;
String[] newTab = new String[1];
addNew = sc.next();
for(int i = 0; i<newTab.length; i++) {
if (newTab[i] == null) {
newTab[i] = addNew;
}
else {
//here i want to create new table greater than first one
}
}
Trying with Array.CopyOf but still got error java.lang.ArrayIndexOutOfBoundsException: 1
Code:
int defTab = 1;
for(int i = 0; i<newTab.length; i++) {
if (newTab[i] == null) {
newTab[i] = addNew;
//f
for(int j=0; j<newTab.length; j++) {
System.out.println("array content "+newTab[j]);
}
}
else {
String[] newTab2 = Arrays.copyOf(newTab, defTab+1);
for(int j = 0; j<newTab2.length; j++) {
if (newTab2[j] == null) {
newTab2[j] = addNew;
//f
for(int k=0; k<newTab2.length; k++) {
System.out.println("array content "+newTab[k]);
}
}
}
}
}

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));
}
}

Categories

Resources