Help with an array


DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

Results 1 to 14 of 14

Thread: Help with an array

  1. #1
    Join Date
    May 2004
    Posts
    37

    Exclamation Help with an array

    Hello,

    I am working on an array program. I have some questions.

    How can I make sure the user cannot enter over 80 characters?

    How can I make sure the user does not enter symbols (*, &, $, etc)?

    How do I use the method:
    public static boolean palindrome(char[] a, int used)? (This will replace checkInput()).

    Any help is appreciated.
    Thanks,
    Eric

    Code:
    public class PalindromeCheck
    {	
    	String charString;
    	char[] a = new char[80];	
    	int used = 0;
    		
    	//INPUT-------------------------------------------------------------------------	
    	public void getInput()
    	{
    		System.out.println("Input a string of characters followed by a period.");
    		System.out.println("You must make sure that you include the period at the end");
    		System.out.println("of the string or else you will not get correct results.\n");
    		charString = SavitchIn.readLine();  
    		
    		//Make sure the user can only enter 80 char max (79 plus the period).
    		//if(a.length > 80) ???
    		
    		//Make sure to ignore case when comparing letters
    														
    		//make sure the input is either letters or blank spaces	
    		
    		char input[] = charString.toCharArray();
    		for(int i = 0; i < (input.length); i++)
    		{
    			if(Character.isLetter(input[i]) || Character.isSpaceChar(input[i]))
    			{
    				//Maybe check for numbers instead so the if statement isn't empty.  What about symbols?	
    			}
    			else
    				System.out.println("The input must be a letter or a white space.");
    				break;
    		}
    					
    		a = charString.toUpperCase().toCharArray(); //toCharArray() converts a string to an array of characters
    		
    		System.out.println("\nThe string of characters you entered is: ");
    		for(int i = 0; i < a.length; i++)	//displays the array to the screen
    		{
    			System.out.print(a[i]);
    		}
    		System.out.println("\nIs this the correct string of characters?");
    		//if(
    		
    		for(int i = 0; i < a.length; i++)	//increments int used
    		{
    			used++;
    		}
    		
    		System.out.println("\nThe length of the string without the period is " + (charString.length()-1));							
    		System.out.println("The number of indexes already used is " + used + ".");	//displays the number of indexes already used
    		System.out.println("The lowest index used is index a[0].");	//displays the lowest index		
    		System.out.println("The highest index used is index a[" + (a.length-1) + "].");	//displays the highest index used
    	}//----------------------------------------------------------------------------------					
    	
    	
    	//---------------------------------------------------------------------------------
    	/***
    	I MUST USE THIS METHOD:
    	//Precondition:  The array a contains letters and blanks in positions a[0] through a[used-1].
    	//Returns true if the string is a palindrome and false otherwise.
    	
    	//public static boolean palindrome(char[] a, int used)
    	
    	//The program will call the preceding method with the array and one other int variable.  
    	//The other int variable keeps track of how much of the array is used (partially filled array).
    	
    	***/
    	//----------------------------------------------------------------------------------
    			
    			
    	//ACTION----------------------------------------------------------------------------
    	public void checkInput()	//check for palindrome
    	{
    		int left = 0;
    		int right = a.length - 2;  // Subtract 2 from length, one for index 0 and one for the period
    		boolean charsMatch = true;
    		
    		while(left <= right && charsMatch)	//compare characters in the characterString
    		{
    			if(a[left] == a[right])		//!!!Make sure to ignore case when comparing letters!!!
    			{
    				left++;
    				right--;
    			}
    			else
    			{
    				charsMatch = false;
    			}
    		}	
    		//RESULTS------------------------------------------------------------------------
    		//display charString and palindrome check results
    		if(charsMatch)
    		{
    			System.out.println("\n\n" + charString + " \nIS A PALINDROME.\n");
    		}
    		else
    			System.out.println("\n\n" + charString + " \nIS NOT A PALINDROME.\n");		
    		
    		//write a loop that checks additional strings until the user requests that the program ends.		
    	}
    	
    	//MAIN--------------------------------------------------------------------------------------	
    	public static void main(String[] args)
    	{
    		PalindromeCheck checkIt = new PalindromeCheck();
    		checkIt.getInput();
    		checkIt.checkInput();
    		//checkIt.giveOutput();
    	}
    		
    }

  2. #2
    Join Date
    Nov 2004
    Location
    Norway
    Posts
    1,560

    try this

    Code:
    import java.io.*;
    
    public class PalindromeCheck {
      String charString;
      char[] a = new char[80];
      int used = 0;
      static InputStreamReader is=new InputStreamReader(System.in);
      static BufferedReader console=new BufferedReader(is);
      //INPUT-------------------------------------------------------------------------
      public String getInput() {
    
        String cmp=null;
    
        while (true) { // loops until first break; statement
          System.out.println("Input a string of max 79 characters followed by a period.");
          System.out.println(
              "You must make sure that you include the period at the end");
          System.out.println(
              "of the string or else you will not get correct results.\n");
          try {
            charString = console.readLine().trim();
          }
          catch (IOException ex) {
            System.out.println("Error occurred");
            ex.printStackTrace();
            continue; //  loop, new input attempt
          }
    
          if(charString.length() ==0) {
              System.out.println("Blank string won't do");
            continue;  //  loop, new input attempt
          }
          //Make sure the user can only enter 80 char max (79 plus the period).
          if(charString.length() > 80) {
            System.out.println("Connot enter more than 79 chars (+ a period)");
            continue;  //  loop, new input attempt
          }
          if (!charString.endsWith(".")) {
            System.out.println(
                "You must make sure that you include the period at the end");
            continue; // loop, new input attempt
          }
          //Make sure to ignore case when comparing letters
          cmp=charString.toLowerCase();
    
          //make sure the input is either letters or blank spaces
    
          byte [] input=charString.getBytes();
          boolean ok=true;
          for (int i = 0; i < (input.length); i++) {
              if (input[i] != ' ') continue; // a blank
              if ((byte)'a' <= input[i] && (byte)'z' >= input[i]) {
                  System.out.println("The input must be a letter or a white space.");
              ok=false;
              break; // break this charcheck loop
            }
          }
          if (!ok) continue; // new input attempt
    
          break; // we've come to here so all is well, break input loop
        }
        String bareString=cmp.substring(0,charString.length()-1).trim(); // there may be blanks before period
    
        System.out.println("\nThe string of characters you entered is: "+charString);
    
        System.out.println("\nThe length of the string without the period is " +bareString.length());
    
        return bareString;
      } //----------------------------------------------------------------------------------
    
      //---------------------------------------------------------------------------------
      /***
               I MUST USE THIS METHOD:
               //Precondition:  The array a contains letters and blanks in positions a[0] through a[used-1].
               //Returns true if the string is a palindrome and false otherwise.
               //public static boolean palindrome(char[] a, int used)
               //The program will call the preceding method with the array and one other int variable.
               //The other int variable keeps track of how much of the array is used (partially filled array).
       ***/
      //----------------------------------------------------------------------------------
    
      //ACTION----------------------------------------------------------------------------
      public void checkInput(String aString) { //check for palindrome
        boolean charsMatch = true;
        byte [] b=aString.getBytes();
        for (int i=0, j=b.length-1; i<b.length; i++, j--) {
          //System.out.println("compare"+(char)b[i]+" "+(char)b[j]);
          if (b[i]!=b[j]) {
            charsMatch=false;
            break;
          }
        }
        //RESULTS------------------------------------------------------------------------
        //display charString and palindrome check results
        if (charsMatch) {
          System.out.println("\n\n" + charString + " \nIS A PALINDROME.\n");
        }
        else
          System.out.println("\n\n" + charString + " \nIS NOT A PALINDROME.\n");
    
          //write a loop that checks additional strings until the user requests that the program ends.
      }
    
      //MAIN--------------------------------------------------------------------------------------
      public static void main(String[] args) {
        PalindromeCheck checkIt = new PalindromeCheck();
        String s=checkIt.getInput();
        checkIt.checkInput(s);
        //checkIt.giveOutput();
      }
    
    }

  3. #3
    Join Date
    May 2004
    Posts
    37

    Different questions

    Some of that code was over my head. I did like the flow of the program though.

    OK, after much time and hard work, I have my program doing most of what I want it to do.

    I still have these questions:

    If the user inputs a 2 for the menu choice before a string is input, I get a NullPointerException error. How can I fix this?

    The boolean palindrome(char, int) is not returning the correct result.

    Thanks in advance,
    Eric

    Code:
    public class PalindromeCheck
    {	
    	String charString;
    	char[] a = new char[80];
    	int i;	
    	int count = 0;
    	boolean charsMatch = true;
    	boolean result;
    	
    	//Do I want to add constructors?
    	
    	//GET INPUT -------------------------------------------------	
    	//PRECONDITION:
    	public void checkInput()
    	{
    		System.out.println("This program will check a string of characters");
    		System.out.println("and determine whether or not the string is a palindrome.");
    		System.out.println("Input a string of characters followed by a period.");
    		System.out.println("You must make sure that you include the period at the end");
    		System.out.println("of the string or else you will not get correct results.");
    		charString = SavitchIn.readLine();  
    													
    		if(charString.length() > 80)//makes sure the user can only enter 80 char max (79 plus the period).
    		{
    			System.out.println("You cannot enter more than 79 characters (plus a period)\n");
    			System.out.println("\nThe program will now exit.\n");			
    			System.out.println("Please run the program again and ");
    			System.out.println("input the correct string of characters.\n");
    			System.exit(0);	//should this do something different?
    		}
    		
    		char a[] = charString.toUpperCase().toCharArray();	//converts a string to an array of characters
    		
    		for(int i = 0; i < (a.length); i++)//makes sure the input is either letters or blank spaces
    		{
    			if(Character.isLetter(a[i]) || Character.isSpaceChar(a[i]))
    			{
    				//Maybe check for numbers instead so the "if" statement isn't empty.  
    				//What about symbols such as &, *, and #?	
    			}
    			else
    				System.out.println("The input must be a letter or a white space.");
    				break;
    		}
    		
    		System.out.println("\nThe string of characters you entered is: ");	//error checking
    		for(int i = 0; i < a.length; i++)	//displays the array to the screen
    		{
    			System.out.print(a[i]);
    		}
    		System.out.println("\nIs this the correct string of characters?");
    		char choice = SavitchIn.readLineNonwhiteChar(); 
    		choice = Character.toUpperCase(choice);
    		if(choice == 'N')
    		{
    			System.out.println("\nThe program will now exit.\n");				
    			System.out.println("Please run the program again and ");
    			System.out.println("input the correct string of characters.\n");
    			System.exit(0);	//should this do something different?	 			
    		}
    		else
    			for(int i = 0; i < a.length; i++)//increments int used once for each array index that is used
    			{
    				count++;
    			}
    				
    		result = palindrome(a, count);
    		System.out.println("\n" + (result));
    		if(result)
    		{
    			System.out.println(charString + " IS A PALINDROME.\n");
    		}
    		else
    			System.out.println(charString + " IS NOT A PALINDROME.\n");
    	}
    	//POSTCONDITION:					
    	//---------------------------------------------------------------------------
    	//PALINDROME
    	//PRECONDITION:  The array a contains letters and blanks in positions a[0] through a[used-1].
    	//Returns true if the string is a palindrome and false otherwise.
    	//The program will call this method with the array and one other int variable.  
    	//The other int variable keeps track of how much of the array is used (partially filled array).
    	
    	public static boolean palindrome(char[] a, int used)
    	{ 
    		int i;
    		for(i = 0; i < used/2 ;i++)
    		{
    			if(a[i] != a[used - i - 1])
    				return false;
    		}
    		return true;
    	}
    	//POSTCONDITION:
    	//--------------------------------------------------------------------------
    	//DISPLAY ARRAY INFO
    	//PRECONDITION:
    	public void displayArrayInfo(int used)
    	{
    		System.out.println("\nCount = " + count);
    		System.out.println("Used = " + used);
    		System.out.println("\nThe length of the string without the period is " + (charString.length()-1));							
    		System.out.println("The number of indexes already used is " + count + ".");	//displays the number of indexes already used
    		System.out.println("The lowest index used is index a[0].");	//displays the lowest index		
    		System.out.println("The highest index used is index a[" + (a.length-1) + "].");	//displays the highest index used	
    	}
    	//POSTCONDITION:
    	//-------------------------------------------------------------------------
    	//EXIT PROGRAM
    	//PRECONDITION:
    	public void exitProgram()		
    	{
    		//boolean repeat = true; //Need a (do while?) loop to continue the program until the user wants to exit	
    		System.out.println("\nThe program is now exiting.\n");
    		System.exit(0);	
    	}
    	//POSTCONDITION:
    	//-------------------------------------------------------------------------	
    	//MAIN MENU
    	//PRECONDITION:
    	public void mainMenu()
    	{
    		char choice;
    		do
    		{	
    			System.out.println("\n\n\n------------------------------------------------------------");
    			System.out.println("------------------------------------------------------------");
    			System.out.println("------This is the main menu.  Please make a selection.------\n");
    			System.out.println("Please press [1] to input a character string.");
    			System.out.println("Please press [2] to display array info.");
    			System.out.println("Please press [3] to exit the program.");
    					
    			choice = SavitchIn.readLineNonwhiteChar();
    		
    			switch(choice)
    			{
    				case '1':	checkInput();
    								break;
    						
    				case '2':  	displayArrayInfo(count);	//gives NullPointerException if this is chosen first
    								break;
    						
    				case '3':	exitProgram();
    								break;	
    						
    				default:		System.out.println("Options 1-3 only please.");
    								System.out.println("Please enter a selection.\n");
    								//break;
    			}		
    		}while(choice != '3');
    	}
    	//POSTCONDITION:
    	//----------------------------------------------------------------------
    	//MAIN
    	//PRECONDITION:	
    	public static void main(String[] args)
    	{
    		PalindromeCheck checkIt = new PalindromeCheck();
    		checkIt.mainMenu();	
    	}
    	//POSTCONDITION:
    }

  4. #4
    Join Date
    Nov 2004
    Location
    Norway
    Posts
    1,560
    Try this solution below, , or better - dont display option 2 until after the input
    is received, or even better - have blank entry as exit-comdition, a 'D' as
    the Display array option and anything else (w. a period) is a line input.

    Code:
    switch(choice) {
    	case '1':	checkInput();
                   break;						
    	case '2':
                   if (charString==null) {   
                      System.out.println("You must use option 1 first");
                      break;
                   }    	
                   displayArrayInfo(count);						  break;						
    	case '3':	exitProgram();
      	  break;		
                default:		
                   System.out.println("Options 1-3 only please.");
    }			}

  5. #5
    Join Date
    May 2004
    Posts
    37
    Yes, that gets rid of the NullPointerException error.

    I am also getting:
    ArrayIndexOutOfBoundsException: 9
    at PalindromeCheck.palindrome(PalindromeCheck.java:89)
    at PalindromeCheck.checkInput(PalindromeCheck.java:67)
    at PalindromeCheck.mainMenu(PalindromeCheck.java:155)
    at PalindromeCheck.main(PalindromeCheck.java:177)

    How is my array getting full? I do not see what I am doing wrong.

    I cannot figure out why boolean palindrome is not returning the correct results.

    Thanks,
    Eric

    Latest code:
    Code:
    char[] a = new char[80];
    	int i;	
    	int count = 0;
    	//boolean charsMatch = true;
    	boolean result;
    	
    	//Do I want to add constructors?
    	
    	//GET INPUT -------------------------------------------------	
    	//PRECONDITION:
    	public void checkInput()
    	{
    		System.out.println("This program will check a string of characters");
    		System.out.println("and determine whether or not the string is a palindrome.");
    		System.out.println("Input a string of characters followed by a period.");
    		System.out.println("You must make sure that you include the period at the end");
    		System.out.println("of the string or else you will not get correct results.");
    		charString = SavitchIn.readLine();  
    													
    		if(charString.length() > 80)//makes sure the user can only enter 80 char max (79 plus the period).
    		{
    			System.out.println("You cannot enter more than 79 characters (plus a period)\n");
    			System.out.println("\nThe program will now exit.\n");			
    			System.out.println("Please run the program again and ");
    			System.out.println("input the correct string of characters.\n");
    			System.exit(0);	//should this do something different?
    		}
    		
    		char a[] = charString.toUpperCase().toCharArray();	//converts a string to an array of characters
    		
    		for(int i = 0; i < (a.length); i++)//makes sure the input is either letters or blank spaces
    		{
    			if(Character.isLetter(a[i]) || Character.isSpaceChar(a[i]))
    			{
    				//Maybe check for numbers instead so the "if" statement isn't empty.  
    				//What about symbols such as &, *, and #?	
    			}
    			else
    				System.out.println("The input must be a letter or a white space.");
    				break;
    		}
    		
    		System.out.println("\nThe string of characters you entered is: ");	//error checking
    		for(int i = 0; i < a.length; i++)	//displays the array to the screen
    		{
    			System.out.print(a[i]);
    		}
    		System.out.println("\nIs this the correct string of characters?");
    		char choice = SavitchIn.readLineNonwhiteChar(); 
    		choice = Character.toUpperCase(choice);
    		if(choice == 'N')
    		{
    			System.out.println("\nThe program will now exit.\n");				
    			System.out.println("Please run the program again and ");
    			System.out.println("input the correct string of characters.\n");
    			System.exit(0);	//should this do something different?	 			
    		}
    		else
    			for(int i = 0; i < a.length; i++)//increments int used once for each array index that is used
    			{
    				count++;
    			}
    				
    		result = palindrome(a, count);
    		System.out.println("\n" + (result));
    		if(result)
    		{
    			System.out.println(charString + " IS A PALINDROME.\n");
    		}
    		else
    			System.out.println(charString + " IS NOT A PALINDROME.\n");
    	}
    	//POSTCONDITION:					
    	//---------------------------------------------------------------------------
    	//PALINDROME
    	//PRECONDITION:  The array a contains letters and blanks in positions a[0] through a[used-1].
    	//Returns true if the string is a palindrome and false otherwise.
    	//The program will call this method with the array and one other int variable.  
    	//The other int variable keeps track of how much of the array is used (partially filled array).
    	
    	public static boolean palindrome(char[] a, int used)
    	{ 
    		int i;
    		for(i = 0; i < used / 2 ;i++)
    		{
    			if(a[i] != a[used - i - 1])
    				return false;
    		}
    		return true;
    		
    		/*
    		int left = 0;
    		int right = a.length - 2;
    		
    		while(left <= right && charsMatch)
    		{
    			if(a[left] == a[right])
    			{
    				left++;
    				right--;
    			}
    			else
    			{
    				charsMatch = false;
    			}
    		}
    		*/	
    	}
    	//POSTCONDITION:
    	//--------------------------------------------------------------------------
    	//DISPLAY ARRAY INFO
    	//PRECONDITION:
    	public void displayArrayInfo(int used)
    	{
    		System.out.println("\nCount = " + count);
    		System.out.println("Used = " + used);
    		System.out.println("\nThe length of the string without the period is " + (charString.length()-1));							
    		System.out.println("The number of indexes already used is " + count + ".");	//displays the number of indexes already used
    		System.out.println("The lowest index used is index a[" + ((a.length-1)-(a.length-1)));	//displays the lowest index		
    		System.out.println("The highest index used is index a[" + (a.length-1) + "].");	//displays the highest index used	
    	}
    	//POSTCONDITION:
    	//-------------------------------------------------------------------------
    	//EXIT PROGRAM
    	//PRECONDITION:
    	public void exitProgram()		
    	{
    		//boolean repeat = true; //Need a (do while?) loop to continue the program until the user wants to exit	
    		System.out.println("\nThe program is now exiting.\n");
    		System.exit(0);	
    	}
    	//POSTCONDITION:
    	//-------------------------------------------------------------------------	
    	//MAIN MENU
    	//PRECONDITION:
    	public void mainMenu()
    	{
    		char choice;
    		do
    		{	
    			System.out.println("\n\n\n------------------------------------------------------------");
    			System.out.println("------------------------------------------------------------");
    			System.out.println("------This is the main menu.  Please make a selection.------\n");
    			System.out.println("Please press [1] to input a character string.");
    			System.out.println("Please press [2] to display array info.");
    			System.out.println("Please press [3] to exit the program.");
    					
    			choice = SavitchIn.readLineNonwhiteChar();
    		
    			switch(choice)
    			{
    				case '1':	checkInput();
    								break;
    						
    				case '2':  	if(charString == null)
    								{
    									System.out.println("\nYou must use option 1 first.\n");
    									break;
    								}
    								displayArrayInfo(count);	//gives NullPointerException if this is chosen first
    								break;
    						
    				case '3':	exitProgram();
    								break;	
    						
    				default:		System.out.println("Options 1-3 only please.");
    								System.out.println("Please enter a selection.\n");
    								//break;
    			}		
    		}while(choice != '3');
    	}
    	//POSTCONDITION:
    	//----------------------------------------------------------------------
    	//MAIN
    	//PRECONDITION:	
    	public static void main(String[] args)
    	{
    		PalindromeCheck checkIt = new PalindromeCheck();
    		checkIt.mainMenu();	
    	}
    	//POSTCONDITION:
    }

  6. #6
    Join Date
    Nov 2004
    Location
    Norway
    Posts
    1,560

    This is odd,

    you say my method was too complicated, yet you insist on implementing
    something that delivers bugs you can't find.

    You're probably "off by one" somewhere in your palindrome check.
    Where is not not so interesting cause the method you have written is
    just not the way to do it. A palindrome is a text string that reads the same
    both ways, so if you take the first and last char, compare those, then the
    second and the second last, then the third anfd the third last...etc
    until you've looped over the whole string both ways without finding different
    chars, then you have a plaindrome.

    You do that like this (nothing complicated works):

    Code:
    //check for palindrome 
      
    public boolean isPalindrome(String aString) {    
        byte [] b=aString.getBytes();
        for (int i=0, j=b.length-1; i<b.length; i++, j--) {      
          if (b[i]!=b[j]) return false;
        }    
        return true;
      }
    mkay ?

  7. #7
    Join Date
    May 2004
    Posts
    37
    I just haven't learned some of the things you were using.

    I'm trying to keep this as simple as I possibly can.

    I am required to use this method:
    Code:
    public  static boolean palindrome(char[] a, int used)
    //int used keeps track of how much of the array is used

  8. #8
    Join Date
    Nov 2004
    Location
    Norway
    Posts
    1,560
    if you get your input strig like this:

    charString = SavitchIn.readLine().trim(); // eliminate leading/trailing blanks
    int ix=charString.lastIndexOf("."); // find periods position in string (at end)
    if (ix<0) {
    /** error, no period at end **/
    } else {
    charString=charString.substring(0,ix); // chop off period
    charString=charString.trim(); // eliminate any spaces before period
    }

    after this charString is a string with no period at end and no leading or traling
    blanks.

    When you declare like:

    char[] a=new char[80];

    and later do this:

    char [] a=charString.toUpperCase().toCharArray();

    then you've redeclared and reallocated a new array, i.e. the
    old a[80] is gone, - the variable a in your program now is (the pointer to) a
    new array of chars that will be of the same length as charString.

    So, if we invoke the palndrome method below, we would do this like:

    boolean isPalindrome=palindrome(a, a.length);

    Code:
    public static boolean palindrome(char [] array, int used) {    
           for (int i=0, j=used-1; i<used; i++, j--) {      
          if (b[i]!=b[j]) return false;
        }    
        return true;
      }

  9. #9
    Join Date
    May 2004
    Posts
    37

    Still out of bounds

    OK, I understand that I am reallocating a new array.

    What is the best way to make sure I do not go over 80 for the array? I am still getting an ArrayIndexOutOfBoundsException.

    Should I write an if statement like this: if(charString >80) ?

    I guess I cannot use a constant like MAX_INDEX = 80.

    Thank you,
    Eric
    Code:
    public class PalindromeCheck
    {	
    	String charString;
    	char[] a = new char[80];
    	int i;	
    	int count = 0;
    	//boolean charsMatch = true;
    	boolean result;
    	
    	//Do I want to add constructors?
    	
    	//GET INPUT -------------------------------------------------	
    	//PRECONDITION:
    	public void checkInput()
    	{
    		System.out.println("This program will check a string of characters");
    		System.out.println("and determine whether or not the string is a palindrome.");
    		System.out.println("Input a string of characters followed by a period.");
    		System.out.println("You must make sure that you include the period at the end");
    		System.out.println("of the string or else you will not get correct results.");
    		charString = SavitchIn.readLine();  
    													
    		if(charString.length() > 80)//makes sure the user can only enter 80 char max (79 plus the period).
    		{
    			System.out.println("You cannot enter more than 79 characters (plus a period)\n");
    			System.out.println("\nThe program will now exit.\n");			
    			System.out.println("Please run the program again and ");
    			System.out.println("input the correct string of characters.\n");
    			System.exit(0);	//should this do something different?
    		}
    		
    		char a[] = charString.toUpperCase().toCharArray();	//converts a string to an array of characters
    		
    		for(int i = 0; i < (a.length); i++)//makes sure the input is either letters or blank spaces
    		{
    			if(Character.isLetter(a[i]) || Character.isSpaceChar(a[i]))
    			{
    				//Maybe check for numbers instead so the "if" statement isn't empty.  
    				//What about symbols such as &, *, and #?	
    			}
    			else
    				System.out.println("The input must be a letter or a white space.");
    				break;
    		}
    		
    		System.out.println("\nThe string of characters you entered is: ");	//error checking
    		for(int i = 0; i < a.length; i++)	//displays the array to the screen
    		{
    			System.out.print(a[i]);
    		}
    		System.out.println("\nIs this the correct string of characters?");
    		char choice = SavitchIn.readLineNonwhiteChar(); 
    		choice = Character.toUpperCase(choice);
    		if(choice == 'N')
    		{
    			System.out.println("\nThe program will now exit.\n");				
    			System.out.println("Please run the program again and ");
    			System.out.println("input the correct string of characters.\n");
    			System.exit(0);	//should this do something different?	 			
    		}
    		else
    			for(int i = 0; i < a.length; i++)//increments int used once for each array index that is used
    			{
    				count++;
    			}
    				
    		result = palindrome(a, count);
    		System.out.println("\n" + (result));
    		if(result)
    		{
    			System.out.println(charString + " IS A PALINDROME.\n");
    		}
    		else
    			System.out.println(charString + " IS NOT A PALINDROME.\n");
    	}
    	//POSTCONDITION:					
    	//---------------------------------------------------------------------------
    	//PALINDROME
    	//PRECONDITION:  The array a contains letters and blanks in positions a[0] through a[used-1].
    	//Returns true if the string is a palindrome and false otherwise.
    	//The program will call this method with the array and one other int variable.  
    	//The other int variable keeps track of how much of the array is used (partially filled array).
    	
    	public static boolean palindrome(char[] a, int used)
    	{ 
    		int left;
    		int right = used - 1;
    		for(left = 0; left < used; left++, right--)
    		{
    			if(a[left] != a[right])
    			{
    				return false;
    			}
    		}
    		return true;
    	
    	}
    	//POSTCONDITION:
    	//--------------------------------------------------------------------------
    	//DISPLAY ARRAY INFO
    	//PRECONDITION:
    	public void displayArrayInfo(int used)
    	{
    		System.out.println("\nCount = " + count);
    		System.out.println("Used = " + used);
    		System.out.println("\nThe length of the string without the period is " + (charString.length()-1));							
    		System.out.println("The number of indexes already used is " + count + ".");	//displays the number of indexes already used
    		System.out.println("The lowest index used is index a[" + ((a.length-1)-(a.length-1)));	//displays the lowest index		
    		System.out.println("The highest index used is index a[" + (a.length-1) + "].");	//displays the highest index used	
    	}
    	//POSTCONDITION:
    	//-------------------------------------------------------------------------
    	//EXIT PROGRAM
    	//PRECONDITION:
    	public void exitProgram()		
    	{
    		//boolean repeat = true; //Need a (do while?) loop to continue the program until the user wants to exit	
    		System.out.println("\nThe program is now exiting.\n");
    		System.exit(0);	
    	}
    	//POSTCONDITION:
    	//-------------------------------------------------------------------------	
    	//MAIN MENU
    	//PRECONDITION:
    	public void mainMenu()
    	{
    		char choice;
    		do
    		{	
    			System.out.println("\n\n\n------------------------------------------------------------");
    			System.out.println("------------------------------------------------------------");
    			System.out.println("------This is the main menu.  Please make a selection.------\n");
    			System.out.println("Please press [1] to input a character string.");
    			System.out.println("Please press [2] to display array info.");
    			System.out.println("Please press [3] to exit the program.");
    					
    			choice = SavitchIn.readLineNonwhiteChar();
    		
    			switch(choice)
    			{
    				case '1':	checkInput();
    								break;
    						
    				case '2':  	if(charString == null)
    								{
    									System.out.println("\nYou must use option 1 first.\n");
    									break;
    								}
    								displayArrayInfo(count);	//gives NullPointerException if this is chosen first
    								break;
    						
    				case '3':	exitProgram();
    								break;	
    						
    				default:		System.out.println("Options 1-3 only please.");
    								System.out.println("Please enter a selection.\n");
    								//break;
    			}		
    		}while(choice != '3');
    	}
    	//POSTCONDITION:
    	//----------------------------------------------------------------------
    	//MAIN
    	//PRECONDITION:	
    	public static void main(String[] args)
    	{
    		PalindromeCheck checkIt = new PalindromeCheck();
    		checkIt.mainMenu();	
    	}
    	//POSTCONDITION:
    }

  10. #10
    Join Date
    May 2004
    Posts
    37

    Is anyone available?

    Can anyone help me figure this out?

    Thanks,
    Eric

  11. #11
    Join Date
    May 2004
    Posts
    37

    Rewriting it

    OK, I am in the process of rewriting it.

    Here is my assignment and the current code:

    Write a program that will accept a string of characters terminated by a period and will determine whether or not the string (without ther period) is a palindrome. You may assume that the input contains only letters and the blank symbol. You may also assume that the input word is at most 80 characters long. Disregard blanks when deciding if a string is a palindrome, and consider uppercase and lowercase versions of the same letter to be equal.

    Your program need not check that the string is a correct English phrase or word. Include a loop that allows the user to check additional strings until he or she request that the program ends. For this exercise, you should define a static method called palindrome that begins as follows:

    Code:
    /**Precondition: The array contains letters and blanks in 
    positions a[0] through a[used-1].Returns true if the string 
    is a palindrome andfalse otherwise.*/
    
    public static boolean palindrome(char[] a, int used)
    Your program will read the input string into an array with base type char and will call the preceding method with the array and one other int variable. The other int variable keeps track of how much of the array is used.

    Code:
    public class Palindrome7 
    {
    	String charString; 
    	int i;
    	int count;
    	//int used;
    	char[] a = new char[80];
    	
    	//checkInput method-----------------------------------------------------------
    	public void checkInput() 
    	{	
    		count = 0;	//Gives ArrayIndexOutOfBounds error if this is not here
    		System.out.println("This program will check a string of characters");
    		System.out.println("and determine whether or not the string is a palindrome.");
    		System.out.println("Input a string of characters followed by a period.");
    		System.out.println("You must make sure that you include the period at the end");
    		System.out.println("of the string or else you will not get correct results.");
    		charString = SavitchIn.readLine();  
    													
    		if(charString.length() > 80)//makes sure the user can only enter 80 char max (79 plus the period).
    		{
    			System.out.println("You cannot enter more than 79 characters (plus a period)\n");
    			System.out.println("\nThe program will now exit.\n");			
    			System.out.println("Please run the program again and ");
    			System.out.println("input the correct string of characters.\n");
    			System.exit(0);	//should this do something different?
    		}
    
    		charString = charString.toLowerCase(); //this makes the string all lower case.
    		 
    		
    		//!!!Make sure the input is only letters and blank spaces
    		//!!!Make sure there is a period at the end of the charString
    		
    		
    		//Puts the charString into the array.
    		for(i = 0; charString.charAt(i) != '.'; i++) //the loop stops when you encounter a period.
    		{
    			if(charString.charAt(i) != ' ') //ignore the space
    			{
    				a[count] = charString.charAt(i); //use count as the array index
    				count++;
    			}			
    		}
    		
    		//Echos back input
    		System.out.println("\nThe string of characters you entered is: ");	//error checking
    		for(i = 0; i < count; i++)	//displays the array to the screen
    		{
    			System.out.print(a[i]);
    		}
    		
    		System.out.println("\nIs this the correct string of characters?");
    		char choice = SavitchIn.readLineNonwhiteChar(); 
    		choice = Character.toUpperCase(choice);
    		if(choice == 'N')
    		{
    			System.out.println("\nThe program will now exit.\n");				
    			System.out.println("Please run the program again and ");
    			System.out.println("input the correct string of characters.\n");
    			System.exit(0);	//should this do something different?	 			
    		}
    		
    		//Checks for palindrome
    		boolean isPalindrome = palindrome(a,count);
    		System.out.println("\n");
    		if(isPalindrome)
    		{
    			System.out.println((isPalindrome) + "  THE STRING: " + charString + " IS A PALINDROME.\n");
    		}
    		else
    			System.out.println((isPalindrome) + "  THE STRING: " + charString + " IS NOT A PALINDROME.\n");
    	}
    	
    	//palindrome method-----------------------------------------------------------
    	public static boolean palindrome(char[] a, int used)
    	{ 
    		int i;
    		for(i = 0; i < (used / 2); i++)
    		{
    			if(a[i] != a[used-i-1])
    				return false;
    		}
    		return true;
    	}
    	
    	//displayArrayInfo method-----------------------------------------------------
    	public void displayArrayInfo(char[] a, int used)
    	{
    		System.out.println("\nThe length of the string without the period is " + (used));							
    		System.out.println("The number of indexes already used is " + (used + 1) + ".");	//displays the number of indexes already used
    		System.out.println("The lowest index used is index a[" + ((a.length-1)-(a.length-1)) + "].");	//displays the lowest index		
    		System.out.println("The highest index used is index a[" + (a.length-1) + "].");	//displays the highest index used	
    	}
    	
    	//exitProgram method----------------------------------------------------------
    	public void exitProgram()		
    	{	
    		System.out.println("\nThe program is now exiting.\n");
    		System.exit(0);	
    	}
    	
    	//mainMenu method-------------------------------------------------------------	
    	public void mainMenu()
    	{
    		char choice;
    		do
    		{	
    			System.out.println("\n\n------------------------------------------------------------");
    			System.out.println("------------------------------------------------------------");
    			System.out.println("------This is the main menu.  Please make a selection.------\n");
    			System.out.println("Please press [1] to input a character string.");
    			System.out.println("Please press [2] to display array info.");
    			System.out.println("Please press [3] to exit the program.");
    					
    			choice = SavitchIn.readLineNonwhiteChar();
    		
    			switch(choice)
    			{
    				case '1':	checkInput();
    								break;
    						
    				case '2':  	if(charString == null)
    								{
    									System.out.println("\nYou must use option 1 first.\n");
    									break;
    								}
    								displayArrayInfo(a, count);	//gives NullPointerException if this is chosen first
    								break;
    						
    				case '3':	exitProgram();
    								break;	
    						
    				default:		System.out.println("Options 1-3 only please.");
    								System.out.println("Please enter a selection.\n");
    								//break;
    			}		
    		}while(choice != '3');
    	}
    	
    	//main method-----------------------------------------------------------------	
    	public static void main(String[] args)
    	{
    		Palindrome7 checkIt = new Palindrome7();
    		checkIt.mainMenu();
    	}
    }

  12. #12
    Join Date
    May 2004
    Posts
    37

    I need help with the finishing steps

    OK, now I have a few questions.

    How do I:

    Make sure the input is only letters and blank spaces?
    Make sure there is a period at the end of the charString?
    If the user inputs the wrong string, how do I allow the user to stay in the program to reinput the correct string?

  13. #13
    Join Date
    May 2004
    Posts
    37
    OK, I am still having some problems.

    I am getting this error:
    java.lang.StringIndexOutOfBoundsException: String index out of range: 3
    at java.lang.String.charAt(Unknown Source)
    at Palindrome7.checkInput(Palindrome7.java:29)
    at Palindrome7.mainMenu(Palindrome7.java:127)
    at Palindrome7.main(Palindrome7.java:158)
    Exception in thread "main"

    Code:
    public class Palindrome7 
    {
    	String charString; 
    	int i;
    	int count;
    	//int used;
    	char[] a = new char[80];
    	
    	//checkInput method-----------------------------------------------------------
    	public void checkInput() 
    	{	
    		count = 0;	//Gives ArrayIndexOutOfBounds error if this is not here
    		System.out.println("This program will check a string of characters");
    		System.out.println("and determine whether or not the string is a palindrome.");
    		System.out.println("Input a string of characters followed by a period.");
    		System.out.println("You must make sure that you include the period at the end");
    		System.out.println("of the string or else you will not get correct results.");
    		charString = SavitchIn.readLine();  
    													
    		if(charString.length() > 80)//makes sure the user can only enter 80 char max (79 plus the period).
    		{
    			System.out.println("\n\nPlease input the correct string of characters.\n ");
    		   error();
    		}
    
    		charString = charString.toLowerCase(); //this makes the string all lower case.
    		
    		//Puts the charString into the array.
    		for(i = 0; charString.charAt(i) != '.'; i++) //the loop stops when you encounter a period.
    		{
    			if(charString.charAt(i) != ' ') //ignore the space
    			{
    				a[count] = charString.charAt(i); //use count as the array index
    				count++;
    			}			
    		}
    		
    		if(charString.charAt(i) != '.')
    		{
    			System.out.println("\n\nPlease input the correct string of characters.\n ");
    		  	error();
    		}
    		
    		for(i = 0; i < count; i++)//makes sure the input is only letters and blank spaces
    		{
    			if(Character.isDigit(a[i]))
    			{
    				System.out.println("\n\nPlease input the correct string of characters.\n ");
    		   	error();	
    			}
    		}
    		
    		//Echos back input
    		System.out.println("\nThe string of characters you entered is: ");	//error checking
    		for(i = 0; i < count; i++)	//displays the array to the screen
    		{
    			System.out.print(a[i]);
    		}
    		
    		System.out.println("\nIs this the correct string of characters?");
    		char choice = SavitchIn.readLineNonwhiteChar(); 
    		choice = Character.toUpperCase(choice);
    		if(choice == 'N')
    		{			
    			System.out.println("\n\nPlease input the correct string of characters.\n ");
    		   error(); 			
    		}
    		
    		//Checks for palindrome
    		boolean isPalindrome = palindrome(a,count);
    		System.out.println("\n");
    		if(isPalindrome)
    		{
    			System.out.println((isPalindrome) + "  THE STRING: " + charString + " IS A PALINDROME.\n");
    		}
    		else
    			System.out.println((isPalindrome) + "  THE STRING: " + charString + " IS NOT A PALINDROME.\n");
    	}
    	
    	//palindrome method-----------------------------------------------------------
    	public static boolean palindrome(char[] a, int used)
    	{ 
    		int i;
    		for(i = 0; i < (used / 2); i++)
    		{
    			if(a[i] != a[used-i-1])
    				return false;
    		}
    		return true;
    	}
    	
    	//displayArrayInfo method-----------------------------------------------------
    	public void displayArrayInfo(char[] a, int used)
    	{
    		System.out.println("\nThe length of the string without the period is " + (used));							
    		System.out.println("The number of indexes already used is " + (used + 1) + ".");	//displays the number of indexes already used
    		System.out.println("The lowest index used is index a[" + ((a.length-1)-(a.length-1)) + "].");	//displays the lowest index		
    		System.out.println("The highest index used is index a[" + (a.length-1) + "].");	//displays the highest index used	
    	}
    	
    	//exitProgram method----------------------------------------------------------
    	public void exitProgram()		
    	{	
    		System.out.println("\nThe program is now exiting.\n");
    		System.exit(0);	
    	}
    	
    	//mainMenu method-------------------------------------------------------------	
    	public void mainMenu()
    	{
    		char choice;
    		do
    		{	
    			System.out.println("\n\n------------------------------------------------------------");
    			System.out.println("------------------------------------------------------------");
    			System.out.println("------This is the main menu.  Please make a selection.------\n");
    			System.out.println("Please press [1] to input a character string.");
    			System.out.println("Please press [2] to display array info.");
    			System.out.println("Please press [3] to exit the program.");
    					
    			choice = SavitchIn.readLineNonwhiteChar();
    		
    			switch(choice)
    			{
    				case '1':	checkInput();
    								break;
    						
    				case '2':  	if(charString == null)
    								{
    									System.out.println("\nYou must use option 1 first.\n");
    									break;
    								}
    								displayArrayInfo(a, count);	//gives NullPointerException if this is chosen first
    								break;
    						
    				case '3':	exitProgram();
    								break;	
    						
    				default:		System.out.println("Options 1-3 only please.");
    								System.out.println("Please enter a selection.\n");
    								//break;
    			}		
    		}while(choice != '3');
    	}
    	
    	//error method----------------------------------------------------------------
    	public void error()
    	{
    		checkInput();
    	}
    	
    	//main method-----------------------------------------------------------------	
    	public static void main(String[] args)
    	{
    		Palindrome7 checkIt = new Palindrome7();
    		checkIt.mainMenu();
    	}
    }

  14. #14
    Join Date
    Nov 2004
    Location
    Norway
    Posts
    1,560

    Nt sure what has happened to the sequence of posts here...

    Anyway:

    Exceeding chars 80: Don't declare the char [] a as [80]. Its doesn't matter
    what you declare it as, the size of the array is determined by the users
    input anyway. Just declare it as:

    char [] a=null;

    It won't be accessed until the user has entered his chars, and that is when
    you allocate it. Just receive the string, chop off the period anf trim it, If
    its then longer than 79 chars you have an error entry. The length of a
    String object is found using the length() method of the String class, and
    its a good idea to declare this limit on top of your code like;

    public final static int MAX_INDEX = 80; // equivalemnt to c's #define directive

    if(charString.length() > MAX_INDEX)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center
 
 
FAQ
Latest Articles
Java
.NET
XML
Database
Enterprise
Questions? Contact us.
C++
Web Development
Wireless
Latest Tips
Open Source


   Development Centers

   -- Android Development Center
   -- Cloud Development Project Center
   -- HTML5 Development Center
   -- Windows Mobile Development Center