The professional, friendly Java community. 21,500 members and growing!

The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.

Studying for a test, can't figure out my code won't work

The question asks to create a program that will read a first and last name from the
keyboard and create a string that consists of the first letter of the first name, followed by
the first four characters of the last name followed by a random two-digit integer (10-99).
You can assume that the last name will have at least four characters in it.
Here's my code:

It runs w/o errors, asks for the first and last names, but the result has been a 3 digit number everytime! The last three times ran it gave me 589, 514, 509, and 496. When I remove all references to the name2.charAt(#), it DOES give the first character of name1.

What have I done wrong? I've looked through my textbook and didn't see any examples that are helpful...

Re: Studying for a test, can't figure out my code won't work

You're adding a bunch of chars together. Chars can be seen as a subset of ints. Adding them together like that is like adding some ints together. You're going to get a number.

Look at the String and Char api for useful functions for String conversion, and add those instead. Adding Strings is actually a shortcut for creating a StringBuilder and appending the Strings. There is no such shortcut for chars.

Re: Studying for a test, can't figure out my code won't work

Thanks KW, the use of substring was the trick. I'm new to java and programming so I'm still fumbling through things from time to time. I sometimes tend to make things harder for myself when I'm learning something new...LOL...

Re: Studying for a test, can't figure out my code won't work

Originally Posted by coolidge

Thanks KW, the use of substring was the trick. I'm new to java and programming so I'm still fumbling through things from time to time. I sometimes tend to make things harder for myself when I'm learning something new...LOL...

Thanks again,

-C

That's true for everybody, so don't be too hard on yourself. You should see me trying to make a basic website with html and css.