Hello,

I'm working on a little project.
I need to have program which:

1. reads textline from user (example: A little cat goes to town)
2. a) reads words what user wants to change to 0 (example word cat to 000)
b) one word to one line and if given only Enter it stops reading and moves to 3.
3. finds and replaces those words

So in the end it prints: A little 000 goes to town


Here is my current code. Im really struckeling.

public static void main(String[] args) {

		
		while (true){
		System.out.println("Line");
		String givenLine = reader.nextLine();
		if (givenLine.matches("end")) break;
		
		
		System.out.println("Words you want to replace");
		String givenReplace = reader.nextLine();

		StringBuffer sb = new StringBuffer(givenLine);

		System.out.println("Original Text : " + sb);

		sb.replace(????);

		System.out.println("Replaced Text : " + sb);
		}
	}

Edited 6 Years Ago by ace22: n/a

You haven't defined "reader" also look at the api of the String and StringBuffer class to find the methods you need and ask specific questions.
Also you will need a condition to exit the loop.

I changed the code. But still no good. This code just changes one character and also works a little oddly.
Any help?

import java.util.Scanner;

public class test {

	public static void replaceWord(StringBuffer word, StringBuffer replacedWord) {
		String conclusion = word.toString().replace(replacedWord, "0");
		word.replace(0, conclusion.length(), conclusion);
	}
	
	public static Scanner reader = new Scanner(System.in);
	
	public static void main(String[] args) {
		
		System.out.println("Give line");
		String line = reader.next();
		
		System.out.println("Word you want to replace");
		String replacedWord = reader.next();
		
		
		
		
		StringBuffer testword = new StringBuffer(line);
		StringBuffer replaced = new StringBuffer(replacedWord);
		replaceWord(testword, replaced);
		System.out.println(testword);
	}

}

Edited 6 Years Ago by ace22: n/a

This article has been dead for over six months. Start a new discussion instead.