문제

I've write this code but i have a problem. I want to print "Hi something else" when i write "replace something else. How can i do that?

import java.util.Scanner;
public class replace something
{
    public static void main(String[] args)
    {
        Scanner cumle = new Scanner(System.in);
        System.out.println("Enter the sentence u want to replace :");
        String str1 = cumle.next();
        if (str1.contains("replace"))
        {
            str1 = str1.replace("replace", "Hi");
            System.out.println("Replaced Sentence: " + str1);
        }
        else
        {
            System.out.println("Sentence doesn't contains that...");
        }

    }

}
도움이 되었습니까?

해결책

First of all, you have to read the whole line with nextLine(), because next() only reads the next token.

Also, if you want to modify the original string, you have to assign the result of replace() to str1:

str1 = str1.replace("replace", "Hi");

Code:

Scanner cumle = new Scanner(System.in);
System.out.println("Enter the sentence u want to replace :");
String str1 = cumle.nextLine();

if (str1.contains("replace")) {
    str1 = str1.replace("replace", "Hi");
    System.out.println("Replaced Sentence: " + str1);
} else {
    System.out.println("Sentence doesn't contains that...");
}

다른 팁

You are printing str1 and not str:

change this:

System.out.println("Replaced Sentence: " + str1);

to this:

System.out.println("Replaced Sentence: " + str);
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top