I need to input a String that contains a single * character, then a second String. The * will be replaced by the second String. So for example, if the user enters the Strings "d*g" and "in", the program outputs ding. The original String must contain only letters of the alphabet, capital or lowercase, spaces and tab, and a single *. The replacement String may be any legal String in Java. If the first String does not contain a * “Error: no *“ should be output. If the first String contains anything other than letters of the alphabet, spaces or tabs then “Error: Incorrect characters“ should be printed. If the first String does not have a * I do not have to check for incorrect characters, only “Error: no *“ should be output.
What I have so far:
import java.io.*;
import static java.lang.System.*;
import java.util.Scanner;
import java.lang.Math;
class Main{
public static void main (String str[]) throws IOException {
Scanner scan = new Scanner(System.in);
char letter;
int i;
System.out.println("Enter the first String:");
String wc = scan.nextLine();
System.out.println("Enter the replacement String:");
String replace = scan.nextLine();
String my_new_str = wc.replaceAll("*", replace);
for (i = 0; i < wc.length(); i++)
{
letter = wc.charAt(i);
if (! (letter == '*')){
System.out.println("Error: no *");}
System.out.println(""+ my_new_str);
}
}
}
I believe you wanted String.replace(CharSequence, CharSequence)
(not replaceAll
that takes a regular expression).
String my_new_str = wc.replaceAll("*", replace);
should be
String my_new_str = wc.replace("*", replace);
You can test it like
String wc = "d*g";
String replace = "in";
System.out.println(wc.replace("*", replace));
And get (as requested)
ding
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.