I have a question regarding StringBuilder. I'm trying to write a program that takes the user input : for example "DOG DOG CAT DOG DOGCAT", then asks the user to input a word they would like to change and what they would like to change it to. It should then replace all occurrences and print the result.
I have a code:
public class ChangeSentence
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Write text: ");
String text = sc.nextLine();
StringBuilder x = new StringBuilder(text);
System.out.println("Write which word would you like to change: ");
String rep = sc.nextLine();
System.out.println("For what do you want to change it: ");
String change = sc.nextLine();
System.out.println(Pattern.compile(x.toString()).matcher(rep).replaceAll(change));
}
}
How should I change it to achieve the result?
Thanks!
**Forgot to mention, I need to use the StringBuilder (without it i know how to write it).
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Write text: ");
original = sc.nextLine();
//StringBuilder x = new StringBuilder(text);
System.out.println("Write which word would you like to change: ");
String replacableWord = sc.nextLine();
System.out.println("For what do you want to change it: ");
String newWord = sc.nextLine();
String output = original.replace(replacableWord ,newWord);
System.out.println(output);
}
You just use the function replace on the original String and the
first parameter is the target String
the
second parameter is the replacement String
Last line should be replaced by following:
System.out.println(text.replaceAll(rep, change));
It's simple. You have to excercise a little
Related
Trying to split out a string and output the penultimate word inputted by the user, but the .split() only seems to be outputting a single string into the array so its not working?
import java.util.*;
public class Random_Exercises_no60 {
public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
System.out.println("Please enter a sentence.");
String sentence = sc.next();
String[] words = sentence.split("\\s+");
System.out.println(words.length); // Just to check the array
System.out.println("Penultimate word " + words[words.length - 2]);
}
}
Problem is not with the split method, rather you should use nextLine instead of next:
String sentence = sc.nextLine();
The answer by #Aomine should resolve your problem. If you really wanted to use Scanner#next() directly, then you could also try setting the scanner's delimiter to be newline:
Scanner sc = new Scanner (System.in);
sc.useDelimiter(Pattern.compile("\\r?\\n"));
Then, calling Scanner#next() should default to returning the next full line.
You can use the whitespace regex
str = "Hello spilt me";
String[] splited = str.split("\\s+");
The split is working correctly. Reading of information from console is correct. Below changes should work.
public class Random_Exercises_no60 {
public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
System.out.println("Please enter a sentence.");
String sentence = sc.nextLine();
String[] words = sentence.split("\\s+");
System.out.println(words.length); // Just to check the array
for (String currentWord : words ) {
System.out.println("The current word is" + currentWord);
}
}}
I am a beginner to java. I try to write a program to read a series of words from the command-line arguments, and find the index of the first match of a given word. Like user can enter "I love apple", and the given word is "apple". The program will display "The index of the first match of ‘apple’ is 2".
What I did so far does not work. Is it my way of storing the input into the string array not correct?
import java.util.Scanner;
public class test {
public static void main(String [] args) {
System.out.println("Enter sentence: ");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
int num=1;
String sentence[]=new String[num];
for(int i=0; i< num; i++) {
sentence[i] = input; // store the user input into the array.
num = num+1;
}
System.out.println("Enter the given words to find the index of its first match: ");
Scanner sc2 = new Scanner(System.in);
String key = sc2.next();
for(int j=0; j<num; j++) {
while (sentence[j].equals(key)) {
System.out.println("The index of the first match of "+key+" is "+j);
}
}
}
}
String array is not required in your solution.
Try this :-
System.out.println("enter sentence ");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
System.out.println("enter the given word to fin the index ");
sc = new Scanner(System.in);
String toBeMatched = sc.nextLine();
if (input.contains(toBeMatched)) {
System.out.println("index is " + input.indexOf(toBeMatched));
} else {
System.out.println("doesn't contain string");
}
I have made the following changes to make your code work. Note you were storing the input string incorrectly. In your code, the entire code was being stored as the first index in the array. You don't need the first for-loop as we can use the function .split() to distinguish each word into a different index in the array. Rest of the code stays as it is.
public class ConfigTest {
public static void main(String[] args) {
System.out.println("Enter sentence: ");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
// Use this to split the input into different indexes of the array
String[] sentence = input.split(" ");
System.out.println("Enter the given words to find the index of its first match: ");
Scanner sc2 = new Scanner(System.in);
String key = sc2.next();
for (int i = 0; i < sentence.length; i++) {
if (sentence[i].equals(key)) {
System.out.println("The index of the first match of " + key + " is " + i);
}
}
}
}
I think you have a scope problem. sentence[] is declared and instantiated in your first forloop. Try moving the declaration outside of the loop and you should do away with the error.
I also noticed a couple of errors. You could try this
public static void main(String[] args) {
// TODO code application logic here
System.out.println("Enter Sentence");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
String sentence[] = input.split("\\s");
System.out.println("Enter Word");
Scanner sc2 = new Scanner(System.in);
String key = sc2.next();
int index = 0;
for(String word : sentence)
{
if(word.equals(key))
{
System.out.println("The index of the first match of " + key + " is " + index);
break;
}
index++;
}
}
Turtle
sentence variable is only defined inside the for loop, it needs to be declared outside it
You can use the first Scanner (sc) declared variable again instead of declaring another one (sc2)
sentence[i] = input -- will mean -- sentence[0] = "I love apple"
Scanner variable can do all the work for you for the input into the array instead of a for loop
String[] a = sc. nextLine(). split(" ");
This will scan an input of new line and separate each string separated by a space into each array.
System.out.println("Enter sentence: ");
Scanner sc = new Scanner(System.in);
String[] sentence = sc. nextLine(). split(" ");
System.out.println("Enter the given words to find the index of its first match: ");
String key = sc.nextLine();
for(int j=0; j<num; j++) {
if (sentence[j].matches(key)) {
System.out.println("The index of the first match of "+ key +" is "+ j);
}
}
Declare the String [] sentence outside the for loop. It is not visible outside the first for block.
The sentence array is created over and over again during the iteration of the for loop. The loop is not required to get the String from the command line.
Edited my answer and removed the use of any for loops, Arrays.asList() will take the words array and fetch the index of the word from the resulting List.
public static void main(String[] args) throws IOException {
System.out.println("Enter sentence: ");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
System.out.println("Enter the given word to find the index of its first match: ");
Scanner wordInput = new Scanner(System.in);
String key = wordInput.next();
String[] words = input.split(" ");
int occurence = Arrays.asList(words).indexOf(key);
if(occurence != -1){
System.out.println(String.format("Index of first occurence of the word is %d", occurence));
}
}
You just need to declare sentence array outside the for loop, as for now, the issue is of scope.For more on the scope of a variable in java . Also, this is not you intend to do, you intended to take input as a command line.
So, the input which you will get will come in String[] args. For more on command line arguments check here.
This program needs to print a.b.c. but it prints a.b.c...
How do I eliminate the last dot in output.
The program has to work with user ending loop with "."
import java.util.Scanner;
public class dots1 {
public static void main(String args[]) {
Scanner s = new Scanner(System.in);
String input;
String output = "";
System.out.println("Hello! I print out an acronym. ");
do {
System.out.println("Please Enter a Character");
input = s.nextLine();
output = output+input+".";
} while (!input.equals("."));
System.out.println(output);
}
}
Because your exit condition is "." and you add it to output and add another dot. Try following:
public static void main(String args[]) {
Scanner s = new Scanner(System.in);
String input = "";
String output = "";
System.out.println("Hello! I print out an acronym. ");
while (true) {
System.out.println("Please Enter a Character");
input = s.nextLine();
if(input.equals("."))
break;
output = output + input + ".";
} ;
System.out.println(output);
}
I use a little trick using a simple check to see if its not the first read.
boolean isFirst=true;
do{
System.out.println("Please Enter a Character");
input = s.nextLine();
if(!isFirst) output="."+output;
isFirst=false;
output = output+input;
}while(!input.equals("."));
Instead of the do... while, you should use the the while function.
while (!input.equals(".") {
}
You have to use substring function in java and remove the last character of the String.
your loop end while you enter a dot in input.
Example given below.
Try this
import java.util.Scanner;
public class dots1 {
Scanner s = new Scanner(System.in);
String input;
String output = "";
System.out.println("Hello! I print out an acronym. ");
do{
System.out.println("Please Enter a Character");
input = s.nextLine();
output = output+input+".";
}while(!input.contains("."));
System.out.println(output.substring(0, output.length() - 2));
}
}
Output of Single Input
output of Multiple Inputs
So basically what I need help I need help doing is removing a word from a sting. I dont know how to use array, char and such just for those who refer me to that.
Output Ex:
Enter a sentence: I really like Jolly Ranchers.
Enter a string: really
I like Jolly Ranchers.
I just need to remove every occurrence of the string from the sentence essentially. Thanks for help in advance!
(Not looking for a handout, perhaps pseudocode or another example.)
Use replaceAll function,
this function gets two params
regex - the string you want to replace
substr- the string to replace it with
example:
newString = str1.replaceAll(regex, substr);
newString is the edited string
str1 is the string you wish to edit
String.replaceAll works for that
package se.samples;
import java.util.Scanner;
public class WordRemover {
static final String welcomeMessage = "Enter a sentence: ",
secondMessage = "Enter a string: ",
resultMessage = "";
static String replace(String source, String that){
return source.replaceAll(that, "");
}
public static void main(String[] args) throws Exception {
System.out.print(welcomeMessage);
try(Scanner s = new Scanner(System.in)){
String input = s.nextLine();
System.out.print(secondMessage);
System.out.println(resultMessage + replace(input, s.nextLine()));
}
}
}
You can go this way :
public static String remove(){
Scanner sc = new Scanner(System.in);
System.out.println("Enter a sentence :");
String sentence = sc .nextLine();
System.out.println("Enter a word :");
String word = sc .nextLine();
String res ="";
for(String words : sentence.split(" ")){
if(!words.equalsIgnoreCase(word)){ //or words!=word if you want to NOT ignore the case
res+=words+" ";
}
}
return res;
}
public static void main(String[] args) {
System.out.println(remove());
}
It looks every word, and keep only the ones who are not equals to the word you enter
Or a more with a more shorter way :
public static String remove(){
Scanner sc = new Scanner(System.in);
System.out.println("Enter a sentence :");
String sentence = sc .nextLine();
System.out.println("Enter a word :");
String word = sc .nextLine();
return sentence.replaceAll(word,"");
}
Please try this
String[] s = originalString.split(" ");
String wordToRemove = StandardInput;
String finalString ="";
for(String word : s){
if(!word.equals(wordToRemove )){
System.out.Print(word);
finalString += word+" ";
}
}
I believe strings have a replace method so try something like str.replace("really", "") or replaceEach if there will be more than one. I suggest looking at the Java API for more functions.
In my assignment I need to get this output:
Enter a word: house
What letter do you want to replace?: e
With what letter do you wish to replace it? w
The new word is housw.
_____________________________________________.
I got the program to work with this code, but now I need to set while loops. Here is my current code.
String word = "";
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a word: " + word);
word = keyboard.nextLine();
String readChar = null;
System.out.print("What letter do you want to replace?: ");
readChar = keyboard.next();
String changeChar;
System.out.print("With what letter do you wish to replace it? ");
changeChar = keyboard.next();
keyboard.close();
System.out.println(word.replaceAll(readChar, changeChar));
System.out.println();
I need to now make my program output this:
Enter a word: house
What letter do you want to replace?: a
There is no a in house.
What letter do you want to replace?: b
There is no a in house.
What letter do you want to replace?: e
With what letter do you wish to replace it? w
The new word is housw.
How would my while loop look to portray this output?
After you read the word and the character you want to replace (plus the character you want to replace it with) you can use replace method from the String class.
Here is an example usage (adapt the variable names to your code)
word = word.replace(letterToReplace, replacementLetter);
So for example
String word = "aba";
word = word.replace('a', 'c');
System.out.println(word); // Prints out 'cbc'
Also here is an obligatory link to the JavaDoc for the replace method:
http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#replace%28char,%20char%29
Okay this is one possible way to implement the edited second part of the question:
public static void main(String[] args) {
String word = "";
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a word: " + word);
word = keyboard.nextLine();
boolean done = false;
do{
String readChar = null;
System.out.print("What letter do you want to replace?: ");
readChar = keyboard.next();
if(word.contains(readChar)){
String changeChar;
System.out.print("With what letter do you wish to replace it? ");
changeChar = keyboard.next();
done = true;
keyboard.close();
System.out.println(word.replace(readChar, changeChar));
}
}
while(!done);
}
I hope you don't mind hard interpretation,Below is the example you can follow the same.
String a = "HelloBrother How are you!";
String r = a.replace("HelloBrother","Brother");
print.i(r);
If you want to replace all of the letters, you can do it like this (working code):
public static void main(String[] args) {
String word = "";
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a word: " + word);
word = keyboard.nextLine();
String readChar = null;
System.out.print("What letter do you want to replace?: ");
readChar = keyboard.next();
String changeChar;
System.out.print("With what letter do you wish to replace it? ");
changeChar = keyboard.next();
keyboard.close();
System.out.println(word.replace(readChar, changeChar));
}
This illustrates what you need to do.
import java.util.Scanner;
public class WordScrambler{
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a word: ");
String word = keyboard.nextLine();
System.out.print("What letter do you want to replace?: ");
char letter = keyboard.next().charAt(0);
StringBuffer out = new StringBuffer(word);
System.out.print("With what letter do you wish to replace it? ");
char changeChar = keyboard.next().charAt(0);
for (int i=0; i<word.length(); ++i)
if(word.charAt(i) == changeChar)
out.setCharAt(i, changeChar);
System.out.println("The new word is "+out);
}
}