4 Replies Latest reply: Jun 26, 2008 5:49 PM by 807601 RSS

    Using the length() method to obtain a substring...

    807601
      Ok, I have this project for a username creator that I have been working on for a while now and I have hit a snag. I can't seem to figure out how to use the substring method for anything more than 1 character. The objective is to create a program that reads the users input from the keyboard and displays that back as the first letter of the first word they entered, the first five letters of the second word, and a random number between 10 and 99. I have the first letter of the first word and the random number working fine, it is the first five letters of the second word that is giving me problems.

      Here is my code so far:

      import java.util.Scanner;

      // Allows for the random number generator to be created
      import java.util.Random;

      public class UsernameGenerator
      {
           public static void main(String[] args)
           {
                Scanner scan = new Scanner (System.in);
                
                // Creates the random number generator
                Random generator = new Random();
                
                String first;
                
                String last;
                
                int x;
                
                System.out.print("What is your first name: ");
                first = scan.nextLine();
                
                System.out.print("What is your last name: ");
                last = scan.nextLine();
                
                // Method will detect the length of the string
           
                
                // Substring will output the first letter of the first name only
                String fName = first.substring(0, 1);
                
                // Substring will output the first five letters of the last name only
                String lName = last.substring(0, 5);
                
                // Assigns to x a random number between 10 and 99
                x = 10 + generator.nextInt(99);
                
                System.out.println(fName + lName + x);
                
           }
      }

      Now, where it says //Method will detect the length of the string, I was trying to use the length() method to detect the length and then use that to allow the program to find the first five letters of the second word. But I keep getting compiling errors for incompatible types.

      For instance, I would try something like this:

      Int y = last.length();
      String lName = y.substring(0, 5);

      But I was getting incompatibility errors.

      I am at a loss for what to do, I have looked through the APIs, but they haven't been much help. And my book doesn't really help with tackling this problem either.

      Thanks!