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:
public static void main(String[] args) {
String name1,name2;
Scanner scan = new Scanner (System.in);
Random rand = new Random ();
int num1;
num1 = rand.nextInt(89) + 10;
System.out.print ("Enter your first name: ");
name1 = scan.nextLine();
System.out.print ("Enter your last name: ");
name2 = scan.nextLine();
System.out.println (name1.charAt (0) + name2.charAt(0) + name2.charAt(1) + name2.charAt(2) + name2.charAt(3) +num1);
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...
Any input would be appreciated...
Thanks,
-C
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
While I'm at it, why use the charAt() function at all? Looks like a job for substring() to me.
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...
Thanks again,
-C
Re: Studying for a test, can't figure out my code won't work
Quote:
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.