Results 1 to 16 of 16
  1. #1
    arson09 is offline Member
    Join Date
    Mar 2010
    Posts
    21
    Rep Power
    0

    Default toUpperCase() method

    Ok, i didn't know whether to put this to my already posted question which is the "String.trim() method help....." post since this is a totally different question, but it relates to the same program..

    What i'm very confused about is how to read a passage from a text file, and convert the first character of each word to a Capital letter.. I'm sure the program has a lot of bugs in it that still needs to be fixed, but i'm trying to work on it piece by piece... The code that i'm confused on right now is the
    Java Code:
    str[i]= the_words[i].substring(0, 1).toUpperCase()+str[i].substring(1);
    , but that's neither here nor there.. The problem i'm having right now is that i'm getting the "variable may not have been initialized" era, and i'm really unsure of how i'm getting it.... That variable that getting the era is "the_words" variable all the way in the last statement(For loop and the print statement)

    Java Code:
    public class project2
    {
       public static void main(String[] args)
       throws java.io.IOException
       {
    
       // Declare Variables
    
          int i;
          int num_lines = 0;
          String infilename;
          String str [] = new String [1000];
          String [] the_words;
    
       // Establish keyboard input stream
    
          Scanner sc = new Scanner(System.in);
    
      // Get required data items from user
      
       // Prompt user for input file name
    
          System.out.print("Enter name of text file: ");
          infilename = sc.nextLine();
    
       // Check for existence of the file
      
          File infile = new File(infilename);
    
      
          if(!infile.exists())
          {
    
             System.out.println("The file" +infilename+ "does not exists.");
             System.out.println("Quitting now. Please try again.");
             System.exit(1);
          }
        
    
        //Open the file for reading
    
          Scanner fsc = new Scanner(infile);
          
        //Read the data in the file line by line
          
          while (fsc.hasNext() )
          {
       
       	str[num_lines] = fsc.nextLine();
          
          	num_lines ++;
          }
       
       	//fsc.close();
          
       // Print text passage
    
          for(i=0; i<num_lines; i++)
      
            System.out.println(str[i]);
          System.out.println();
          System.out.println();
          
       // Count the total number of words in passage
          int sum = 0;
             
          for(i=0; i<num_lines; i++)
          {
            the_words = str[i].trim().split("\\s+");
    
       // Calcualte amount of words
           sum += the_words.length;
        
          }
       // Print the amount of words
          System.out.println("Amount of words in passage: "+sum);
          System.out.println();
          System.out.println();
          
       // Capitalize first letter of every word
       
       	
         for(i = 0; i<the_words.length; i++)
         {
          if (i==0)
           {
            // Capitalize the first letter of the string
       	 str[i]= the_words[i].substring(0, 1).toUpperCase()+str[i].substring(1);
            }
         }
    
          System.out.println(the_words[i]);
      
            
          
       }
          
    }
    Last edited by arson09; 04-28-2010 at 04:51 PM.

  2. #2
    iluxa is offline Senior Member
    Join Date
    Mar 2010
    Posts
    266
    Rep Power
    5

    Default

    Java Code:
    str[i]= the_words[i].substring(0, 1).toUpperCase()+str[i].substring(1);
    should be

    Java Code:
    str[i]= the_words[i].substring(0, 1).toUpperCase()+[B]the_words[/B][i].substring(1);

  3. #3
    arson09 is offline Member
    Join Date
    Mar 2010
    Posts
    21
    Rep Power
    0

    Default

    Thank you for the correction.. I knew that piece of code was definitely wrong, even though i thought i was much more off than that. But why is my variable "the_words" getting the "variable my not have been initialized" era when compiled though??

    for(i = 0; i<the_words.length; i++)
    and
    System.out.println(the_words[i]);

  4. #4
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,224
    Rep Power
    20

    Default

    Please learn to indent your code correctly.
    Unindented code is very hard to read.

    The only places you initialise the_words (also learn the Java coding standards) is inside a conditional statement (a for loop) which may well not be executed...what if num_lines is 0?

  5. #5
    arson09 is offline Member
    Join Date
    Mar 2010
    Posts
    21
    Rep Power
    0

    Default

    Quote Originally Posted by Tolls View Post
    Please learn to indent your code correctly.
    Unindented code is very hard to read.

    The only places you initialise the_words (also learn the Java coding standards) is inside a conditional statement (a for loop) which may well not be executed...what if num_lines is 0?



    Sorry about that... But question, as of what you see, other than where my "the_words" is initialized, is what i'm trying to do on the right path??

  6. #6
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,224
    Rep Power
    20

    Default

    No idea.
    I tend to only answer the "my code is broke" questions, and only then if they're fairly clear.
    I do enough code reviewing in the day as it is.

  7. #7
    arson09 is offline Member
    Join Date
    Mar 2010
    Posts
    21
    Rep Power
    0

    Default

    Quote Originally Posted by Tolls View Post
    No idea.
    I tend to only answer the "my code is broke" questions, and only then if they're fairly clear.
    I do enough code reviewing in the day as it is.


    Fair enough.. Thank you though for the initialization reason though.

  8. #8
    arson09 is offline Member
    Join Date
    Mar 2010
    Posts
    21
    Rep Power
    0

    Default

    Still having problems with this.. Just can't seem to get it... I added another piece to the code towards the bottom.. It replaces all instances of The word "The" to the word "La" and "the" to the word "la."


    But i'm still confused on how to go about capitalizing the first characters in each word. My ToUpperCase() method is all jacked up.

    Java Code:
    //Change all occurences of the word "The" to the word "La" and the word "the" to the word "la"
          
         for(i = 0; i<num_lines; i++)
          
           {   
                    String s1 = " "+str[i]+" ";
                    String s2 = s1.replaceAll(" the ", " la ");
                    String s3 = s2.replaceAll(" The ", " La ");
             
          }
           
       // Capitalize first character of each word  
    
           int k =0;
             
               while(k<s1.length())
               {
                 if(s1.charAt(k) == " ")
                  s2 = s2+s1.charAt(k)+s1.toUpperCase(str.charAt(k+1));
          
                    else
                      s2= s2+s1.charAt(k);
          
                 k++;
                 k++;
               }
                    
              
         // Prints the passage with first character capitalized     
          System.out.println(s2);
    
         // Prints the word replacement passage
          System.out.println(s3);
       
    
           
       }     
               
    }



    This is the compile error message i'm getting:

    Java Code:
    project2.java:126: incomparable types: char and java.lang.String
                 if(s1.charAt(k) == " ")
                                 ^
    
    project2.java:127: cannot find symbol
    symbol  : method charAt(int)
    location: class java.lang.String[]
                  s2 = s2+s1.charAt(k)+s1.toUpperCase(str.charAt(k+1));
                                                         ^
    2 errors





    '
    Java Code:
    public class project2
    {
       public static void main(String[] args)
       throws java.io.IOException
       {
    
       // Declare Variables
      
          int i;
          int num_lines = 0;
          String infilename, s1, s2, s3;
          String str [] = new String [1000];
          String [] the_words = new String[0];
          char [] charArr;
      
       // Establish keyboard input stream
         Scanner sc = new Scanner(System.in);
      
       // Get required data items from user
    
       // Prompt user for input file name
     
          System.out.print("Enter name of text file: ");
          infilename = sc.nextLine();
        
       // Check for existence of the file
       
          File infile = new File(infilename);
          
          
          if(!infile.exists())
          {
          
             System.out.println("The file" +infilename+ "does not exists.");
             System.out.println("Quitting now. Please try again.");
             System.exit(1);
         }
          
      
        //Open the file for reading
    
          Scanner fsc = new Scanner(infile);
     
        //Read the data in the file line by line
          //int sum = 0;
          while (fsc.hasNext() )
          {
          
            str[num_lines] = fsc.nextLine();
    
             //for(i=0; i<str.length;i++)
             //{
               //if(i ==0)
                //{the_words = str[i].trim().split("\\s+");
                  //sum += the_words.length}
             //}
           num_lines ++;
             
          }
          
      
            //fsc.close();
    
          
       // Print text passage
          
          for(i=0; i<num_lines; i++)
          
          System.out.println(str[i]);
          System.out.println();
          System.out.println();
               
                
       // Count the total number of words in passage
          int sum = 0;
    
          for(i=0; i<num_lines; i++)
          {
           the_words = str[i].trim().split("\\s+");
    
           sum += the_words.length;
             
          }
       // Print the amount of words
          System.out.println("Amount of words in passage: "+sum);
          System.out.println();
          System.out.println();
          
       // Change all occurrences of the word "The" to the word "La" and the word "the" to the word "la"
          
         for(i = 0; i<num_lines; i++)
          
           {   
                    s1 = " "+str[i]+" ";
                    s2 = s1.replaceAll(" the ", " la ");
                    s3 = s2.replaceAll(" The ", " La ");
             
          }
           
       // Capitalize first character of each word  
    
           int k =0;
             
               while(k<s1.length())
               {
                 if(str.charAt(k) == " ")
                  s2 = s2+s1.charAt(k)+s1.toUpperCase(str.charAt(k+1));
          
                    else
                      s2= s2+s1.charAt(k);
          
                 k++;
                 k++;
               }
                    
             
          System.out.println(s2);
          System.out.println(s3);
       
    
           
       }     
               
    }
    Last edited by arson09; 04-30-2010 at 07:38 AM.

  9. #9
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,224
    Rep Power
    20

    Default

    The first error is because you are comparing a char with a string. If you want a char you use single quotes round a single character.

    So ' ', not " ".

    The second error seems to be that "str" is a String[] and not a String, so charAt won't work. You'll need to tell it which String you want to do charAt on.

  10. #10
    arson09 is offline Member
    Join Date
    Mar 2010
    Posts
    21
    Rep Power
    0

    Default

    Quote Originally Posted by Tolls View Post
    The first error is because you are comparing a char with a string. If you want a char you use single quotes round a single character.

    So ' ', not " ".

    The second error seems to be that "str" is a String[] and not a String, so charAt won't work. You'll need to tell it which String you want to do charAt on.


    Is this the correct route to go???


    Java Code:
     while(k<s1.length())
               {
                 if(s1.charAt(k) == ' ')
                  s2 += s1.charAt(k).s1.toUpperCase(s1.charAt(k+1));
           
                    else
                      s2 += s1.charAt(k);
          
                 k++;
                 k++;
               }


    Compile error code:

    Java Code:
    project2.java:127: char cannot be dereferenced
                  s2 += s1.charAt(k).s1.toUpperCase(s1.charAt(k+1));
                                    ^

  11. #11
    gcalvin is offline Senior Member
    Join Date
    Mar 2010
    Posts
    952
    Rep Power
    5

    Default

    Quote Originally Posted by arson09 View Post
    Compile error code:

    Java Code:
    project2.java:127: char cannot be dereferenced
                  s2 += s1.charAt(k).s1.toUpperCase(s1.charAt(k+1));
                                    ^
    Take a good look at what the compiler is telling you, and think about it. What does "charAt(k).s1" mean? If you don't know what it means, then why is it in your code?

    When you catch yourself just changing things and trying to recompile, without understanding what's going on, it's time to slow down, take a step back, and simplify. Believe me, we've all been there. But if you don't understand exactly what your code is doing, then you need to slow down and test things one at a time.

    -Gary-

  12. #12
    arson09 is offline Member
    Join Date
    Mar 2010
    Posts
    21
    Rep Power
    0

    Default

    Quote Originally Posted by gcalvin View Post
    Take a good look at what the compiler is telling you, and think about it. What does "charAt(k).s1" mean? If you don't know what it means, then why is it in your code?

    When you catch yourself just changing things and trying to recompile, without understanding what's going on, it's time to slow down, take a step back, and simplify. Believe me, we've all been there. But if you don't understand exactly what your code is doing, then you need to slow down and test things one at a time.

    -Gary-

    Sir, i see what your saying, and i see that it's a mistake, and you are absolutely correct.. That's exactly what i've been doing these past few days.. I'm just still REALLY confused about this conversion... It seems like no matter what i do, i still get the char cannot be dereferenced compile error or more compile error codes than what i originally started out with.. I know exactly what i want to do. I'm just really confused on how exactly to put it into code... Should i be using the substring method? If charAt(k) is a space, how do i increment one and capitalize the very next word, etc?? This is where i'm confused at..

  13. #13
    gcalvin is offline Senior Member
    Join Date
    Mar 2010
    Posts
    952
    Rep Power
    5

    Default

    I would do it something like this:

    Java Code:
    create a StringBuilder to build my result string
    create a boolean capitalize variable and initialize it to true
    for each character in the original string
            if character is a space (or period or newline or question mark or tab or whatever else might come before a new word)
                    set capitalize to true
                    append character to result StringBuilder
            else
                    if capitalize
                            append Character.toUpperCase(character) to result StringBuilder
                            set capitalize to false
                    else
                            append character to result StringBuilder
    return the result StringBuilder's toString()
    There may be a way to do it more efficiently, but that's basically the idea.

    -Gary-

  14. #14
    arson09 is offline Member
    Join Date
    Mar 2010
    Posts
    21
    Rep Power
    0

    Default

    Question....Seeing as though i'm reading in the file with:

    Java Code:
      //Read the data in the file line by line
          while (fsc.hasNext() )
          {
           	str[num_lines]= fsc.nextLine();
            num_lines ++;
          }
          	fsc.close();

    And what i'm trying to do with the overall code is:

    1: Capitalize the first character of each word in the passage

    2. Replace all instances of "The" to "La(Already done)

    3. Print the longest word in the passage that does not end with a 's.'

    4. Print a frequency table for the 6 prepositions "of" "to" "in" "for" "with" and "on" (How many times they occur in the passage and and their percentage

    5. A biagram of two consecutive letters within a word.. Showing biagrams for the most frequently occuring biagram, 2nd most frequent occured biagram, and so on..


    So my question is, since the program requires that i identify and
    extract individual words from the text passage. Would it be helpful if i convert the string array into a regular string?
    Something like:

    Java Code:
    String  str1+= str[num_lines];
    I've tried using:
    Java Code:
    the_words = str.trim().split("\\s+");
    in which returns an array of strings to my already declared
    Java Code:
    String the_words [];
    ... I just don't know how to implement it in my code though.
    Last edited by arson09; 05-03-2010 at 03:59 AM.

  15. #15
    gcalvin is offline Senior Member
    Join Date
    Mar 2010
    Posts
    952
    Rep Power
    5

    Default

    No, you can't append a String array onto a String like that. I don't see the need to read the file into a String array in the first place. Why don't you just handle the lines one by one as you read them?

    -Gary-

  16. #16
    arson09 is offline Member
    Join Date
    Mar 2010
    Posts
    21
    Rep Power
    0

    Default

    Quote Originally Posted by gcalvin View Post
    No, you can't append a String array onto a String like that. I don't see the need to read the file into a String array in the first place. Why don't you just handle the lines one by one as you read them?

    -Gary-


    The only way we've learned so far is by reading the passage into an array..

Similar Threads

  1. Replies: 2
    Last Post: 03-26-2010, 06:12 PM
  2. ArrayLists compareTo method, equals method
    By random0munky in forum New To Java
    Replies: 2
    Last Post: 10-26-2009, 08:20 PM
  3. Replies: 2
    Last Post: 02-24-2009, 05:32 PM
  4. Replies: 29
    Last Post: 09-25-2008, 08:55 PM
  5. cannot call private method from static method
    By jon80 in forum New To Java
    Replies: 3
    Last Post: 05-07-2008, 09:37 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •