Jump to content

My Awesome Program doesn't work. Stupid array out-of-bounds

- - - - -

  • Please log in to reply
20 replies to this topic

#1
An Alien

An Alien

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 260 posts
UPDATE/EDIT:
I updated my code from last time so please check it again.
I have made some of the variables in my class public so I can test out what is causing the problem.
I know where the problem is coming from, but IDK how to solve it.
It will be underlined in the code.


Not really awesome, but it's my first OO program with separate classes and methods instead of just one huge class of messy code. Basically, the goal of this program is to check two strings and see if they are palindromes or not. A palindrome is basically an inverse string.
Palindrome example:
He was
Was he
or
Never odd or even
Even or odd never

So after a user enters two strings, the program check to see if they are equal after resorting the second string and comparing it with the first.

If I'm not clear enough, tell me so I can explain this further.

Code:
import java.util.Scanner;

public class main {

	public static void main(String[] args) {

		boolean isPalendrome;

		Scanner io = new Scanner(System.in);

		String str1;

		String str2;

		System.out.println("Please enter the first part of your string");

		str1 = io.nextLine();

		

		System.out.println("Enter second part of your string");

		str2 = io.nextLine();

		

		PChecker pc = new PChecker(str1, str2);

		isPalendrome = pc.checker();

		System.out.println("Test: " + isPalendrome); //TEST

		System.out.println("Test: " + pc.compare);

		System.out.println("Test: " + pc.newStr);

		if (isPalendrome == true)

			System.out.println("The two strings are inverse so this is a palendrome");

		

		else if (isPalendrome == false)

			System.out.println("It is not a palendrome!");

		

		

		

	}

}


I HAVE UNDERLINED THE LINE THAT I LAST TRACED TO BE THE PROBLEM
public class PChecker implements Comparable<String> {


	private String myStr1;

	private String myStr2;

	private String[] sort;

	public boolean checker;

	public int compare;

	public String newStr = null; //this is where new string will be stored

	


	public PChecker(String str1, String str2){

		

		myStr1 = str1;

		myStr2 = str2;

		sort = new String[getSpace()];

	}

	

	private int getSpace() {

		int space = 1; //if no spaces, just word, needs 1 space for it, zero will cause error

		

		for(int x = 0; x < myStr2.length(); x++){

			if(myStr2.substring(x, x+1).equals(" "))

				space++;

		}

		return space;

	}


	public boolean checker(){

		

		compare = compareTo(resort());

		if(compare == 0)

		return checker = true;

		

		else return checker = false;

		

	}

	

	

	public int compareTo(String str2) {

		if (myStr1.equalsIgnoreCase(str2) ){

		return 0;}

		else return 1;

		

	}

	

	//my first awesome algorithm to sort ****. I'm awesome :D

	public String resort(){

		

		

		for (int x = 0; x < myStr2.length(); x++){ //for x is less than the length of string

			final String BLANK = " ";

			int count = 0; //count incremented for letters, and skipped for words

			if(!(myStr2.substring(x, x+1).equals(BLANK))){ //store any non space/letters in array

			sort[count] += 	myStr2.substring(x, x+1); //add them up in the same element of array

			}

			else if (myStr2.substring(x, x+1).equals(BLANK)){

				count++;

				sort[count] += BLANK;

				count++;

			}

		}

		

		for (int x = sort.length - 1; x == 0; x--)

		[U]newStr += sort[x];

		

		return newStr;[/U]

	}

	

	

}



Edited by An Alien, 25 April 2011 - 09:32 AM.


#2
An Alien

An Alien

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 260 posts
I think my while loop may be the problem, I'm not sure if it is correct.

#3
Alexander

Alexander

    It's Science!

  • Moderators
  • 4,118 posts
  • Location:Vancouver, Eh! Cleverness: 200
In your for loop, you likely mean < x and not <= x.

The latter will loop length + 1 times.
Be sure to read the updated FAQ! || Health is achieved through the same 10,000 steps.
If a suggested code/method fails, informing us is less important than telling us why or what errors occurred.

#4
An Alien

An Alien

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 260 posts
Yeah, I forgot to change that back, I was testing to see if that was causing the problem but it's not. Something else is.

#5
An Alien

An Alien

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 260 posts
I know I'm on the brink of figuring this out. I've done some major changes to the code and I think I will find the solution soon. So you guys don't have to help me anymore unless I post again that I was unable to figure it out by myself. It's one of those programs that really makes me think. Those for loops and increments can get confusing sometimes. :P

#6
An Alien

An Alien

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 260 posts
Okay, I have updated, and underlined the part that I cannot figure out. Please help.
Also, if a mod can, change the title to something else since array out of bounds is a noob error and this is not a noob error happening right now, lol. Maybe to something like: "I'm stuck, help. Before I destroy my computer"

#7
wim DC

wim DC

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 2,084 posts
  • Programming Language:Java, JavaScript, PL/SQL
  • Learning:Java
Note that that loop will only run if x==0, you propably want x>=0

for (int x = sort.length - 1; x >= 0; x--)

	newStr += sort[x];

Also, you never initalise newStr. newStr is null, and I think that doing += may result in a nullpointer. Better declare it up top like
String newStr = "";

I don't see an outOfBounds happening there tho. here however:

              for (int x = 0; x < myStr2.length(); x++){ //for x is less than the length of string

			final String BLANK = " ";

			int count = 0; //count incremented for letters, and skipped for words

			if(!(myStr2.substring(x, x+1).equals(BLANK))){ //store any non space/letters in array

			sort[count] += 	myStr2.substring(x, x+1); //add them up in the same element of array

			}

			else if (myStr2.substring(x, x+1).equals(BLANK)){

				count++;

				sort[count] += BLANK;

				count++;

			}

		}

It is likely to happen.

Because you do x+1 inside the loop, you should also do -1 at the loop condition.
Also note that .length returns the number of characters, but substring works with indexes, meaning substring is zero-based, and the length() is not.
Image a 4 letter string "home"
home.length() = 4;
So you loop untill x=3;
inside the loop
home.substring(3, 3+1);
Since home has nothing at index 4 (indexes are 0,1,2,3) it will or should throw outOfBounds there.

so, change the loop to

 for (int x = 0; x < myStr2.length() - 1 ; x++){



#8
An Alien

An Alien

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 260 posts

wim DC said:


I don't see an outOfBounds happening there tho. here however:

[CODE]

 for (int x = 0; x < myStr2.length() - 1 ; x++){


But shouldn't it already take care of it without that minus one, since I don't have x <= string.length, it'll always be one less automatically. Is that right?

And thank you for finding my other mistakes.

#9
An Alien

An Alien

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 260 posts
Okay, I think the main problem is the array having unnecessary elements. I just tested some input and test#3 shows:

Quote

Please enter the first part of your string
he was
Enter second part of your string
was he
Test: false
Test: 1
Test: null nullwashe
It is not a palendrome!
This is printing out the newStr and that means that nothing in my algorithm is working correctly which makes me very very sad :'(

#10
wim DC

wim DC

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 2,084 posts
  • Programming Language:Java, JavaScript, PL/SQL
  • Learning:Java
ehm, in getSpace() you calculate the number of words. You then use this number to create the sort array. So the sort array can hold all the words.
In the loop @ resort() you also put spaces in that sort array, but since the sort array is created to hold only words, and not spaces it will become too big -> outOfBounds

2 possible solutions:
- Don't store spaces in the sort array
- Change getSpace() to also count the spaces

PS:
put

int count = 0; //count incremented for letters, and skipped for words

final String BLANK = " ";

Before the for-loop, outside of it. You don't want it to run this code every loop.

Edit: you were right about the loop thing. subString of the String class works with the 2nd index exlusively, so it's ok to have it 1 bigger than the index.

#11
An Alien

An Alien

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 260 posts
Well actually, what I planned to do is create an array which holds the string. Each element holds one word so I can re write it backwards. And a space has an array space/element for itself.
So for a string like this: He was
sort[0] should have: He
sort[1] should have: "_" <space>
sort[2] should have: "was"

The reason I choose to do this is now I can add the array backwards or print in backwards and get the inverse array so the sort array contains 2 elements now (well it should).
newStr = sort[2] += [1] += [0] which should equal: "was_he". That is my intent with this program.

Lets say that it was one big word like 'racecar"
And the getspace starts with 1 because there are no spaces and creating an array with 0 elements would cause an exception. That is why I start with 1 and then increment space for every " ". Only the spaces have their own elements, the letters in each word share 1 element.
Edit: Okay, I'm wrong about this. I see now that I have to count the words too. You were right, thanks.

#12
wim DC

wim DC

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 2,084 posts
  • Programming Language:Java, JavaScript, PL/SQL
  • Learning:Java
Well, then getSpace should also take into account spaces:

private int getSpace() {

        int space [B]= 2[/B]; //if no spaces, just word, needs 1 space for it, zero will cause error


        for (int x = 0; x < myStr2.length(); x++) {

            if (myStr2.substring(x, x + 1).equals(" ")) {

                space [B]+= 2;[/B]

            }

        }

        return space [B]- 1[/B];

    }

Or shorter:

private int getSpace() {

    return myStr2.split(" ").length * 2 - 1;

}






1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users