PDA

View Full Version : Replace method in Java


saxchick1
02-21-2009, 02:06 AM
I have this application that I am working, would greatly appreciate it if I got an answer soon. In my replace method, I am suppose to replace the letter A and the digit 8 with an *. The statements that I have in my code only executes the A with an *, but not the 8 with an *. How can I solve my problem?

Here is my code:
import java.util.Scanner;
import java.util.Random;

public class Echo
{
public static void main (String[]args)
{
String ID;
String firstName;
String lastName;
int num;

Scanner scan=new Scanner(System.in);

System.out.println("Enter first name: ");
firstName=scan.nextLine();

System.out.println("Enter last name: ");
lastName=scan.nextLine();
System.out.println();

Random generator = new Random();
num=generator.nextInt(16)+15;

ID = firstName.charAt(0) + lastName.substring(0, 3) +num;
System.out.println(ID);
System.out.println();

ID=ID.toUpperCase();
System.out.println(ID);
System.out.println();

ID=ID.replace('A','*');
ID=ID.replace('8','*');
System.out.println(ID);
System.out.println();

}
}

Old Pedant
02-22-2009, 12:14 AM
I don't see why that doesn't work.

Did you use 8 in a test case, to be sure it really isn't working???

For example, enter "Adam" for the first name and "L8ter" for the last name.

What do you get???

**********

I would point out that you'd get a minor efficiency boost by using replaceAll( ) to do both replacements at once. But that's really minor.