I am having trouble getting my program to produce the exact output I would like it to. My program currently will remove any one instance of a string in a sentence the user inputs (Ex: Sentence- Hello there– String to be removed Hello and Output there).
What I would like to do is add something else so that the program will remove any and all instances of the string the user would like omitted (Ex: Hello there there in my current program, it would output Hello there. What I would like is it to simply print Hello). Can someone give me any idea on how to implement this. Thanks!
(Im also rather new to coding, so if you have an input on my code as is, please feel free to correct it)
Here is my current code:
import java.util.Scanner;
public class RemoveWord
{
Scanner scan = new Scanner(System.in);
String sentence;
String word;
public void removing()
{
System.out.println("Please enter a sentence");
sentence = scan.nextLine();
System.out.println("Please enter a word you would like removed from the sentence");
word = scan.nextLine();
int start = sentence.indexOf(word), end=0;
while(start!=-1)
{
sentence = sentence.substring(0, start) + sentence.substring(start+word.length());
end = start+word.length();
if(end>=sentence.length())
break;
start = sentence.indexOf(word, end);
}
System.out.println(sentence);
}
}
public class RemoveWordR
{
public static void main(String[]args)
{
RemoveWord r1 = new RemoveWord();
r1.removing();
}//main
}//class
Your problem is with end, because indexOf(x,y) check for occurrence of x after index y. It is int indexOf(String str, int fromIndex)
while(start!=-1)
{
sentence = sentence.substring(0, start) + sentence.substring(start+word.length());
end = start+word.length();
if(end>=sentence.length())
break;
start = sentence.indexOf(word, 0); //this line must be 0 or nothing
}
replaceAll() method provided by a string should replace all occurrences of a given word in the string
Example:
sentence.replaceAll("there","")
or
sentence.removeAll("there")
Related
My program has a String inputted Eg. hello i am john who are you oh so i see you are also john i am happy
my program then has a keyword inputted Eg. i (the program doesn't like capitals or punctuation yet)
then it reads the initial String and finds all the times it mentions the keyword + the word after the keyword, Eg. i am, i see, i am.
with this is finds the most common occurrence and outputs that second word as the new keyword and repeats. this will produce
i am john/happy (when it comes to an equal occurrence of a second word it stops (it is meant to))
What i want to know is how i find the word after the keyword.
package main;
import java.util.Scanner;
public class DeepWriterMain {
public static void main(String[] args) {
String next;
Scanner scanner = new Scanner(System.in);
System.out.println("text:");
String input = scanner.nextLine();
System.out.println("starting word:");
String start = scanner.nextLine();
input.toLowerCase();
start.toLowerCase();
if (input.contains(start)) {
System.out.println("Loading... (this is where i find the most used word after the 'start' variable)");
next = input.substring(5, 8);
System.out.println(next);
}else {
System.out.println("System has run into a problem");
}
}
}
If you use split to split all your words into an array, you can iterate through the array looking for the keyword, and if it is not the last in the array, you can print the next word
String arr [] = line.split(" ");
for (int i = 0; i < arr.length -1; i++) {
if (arr[i].equalsIgnoreCase(keyword)) {
sop(arr[i] + " " arr[i + 1]);
}
if it is not the last in the array, iterate only to length - 1
The String class includes a method called public int indexOf(String str). You could use this as follows:
int nIndex = input.indexOf(start) + start.length()
You then only need to check if nIndex == -1 in the case that start is not in the input string. Otherwise, it gets you the position of the first character of the word that follows. Using the same indexOf method to find the next space provides the end index.
This would allow you to avoid a linear search through the input, although the indexOf method probably does one anyway.
I am new to Stackoverflow and this is my first time asking a question. I have searched my problem thoroughly, however, could not find an appropriate answer. I am sorry if this has been asked. Thank you in advance.
The question is from Hyperskill.com as follows:
Write a program that reads five words from the standard input and outputs each word in a new line.
First, you need to print all the words from the first line, then from the second (from the left to right).
Sample Input 1:
This Java course
is adaptive
Sample Output 1:
This
Java
course
is
adaptive
My trial to solve it
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
/* I have not initialized the "userInput" String.
* I know that String is immutable in Java and
* if I initialize it to an empty String ""
* and read a String from user.
* It will not overwrite to the "userInput" String.
* But create another String object to give it the value of the user input,
* and references the new String object to "userInput".
* I didn't want to waste memory like that.
*/
String userInput;
String[] userInputSplitFirstLine = new String[3];
String[] userInputSplitSecondLine = new String[2];
Scanner scan = new Scanner(System.in);
userInput = scan.nextLine();
userInputSplitFirstLine = userInput.split("\\s+");
userInput = scan.nextLine();
userInputSplitSecondLine = userInput.split("\\s+");
for(String firstLineSplitted: userInputSplitFirstLine) {
System.out.println(firstLineSplitted);
}
for(String secondLineSplitted: userInputSplitSecondLine) {
System.out.println(secondLineSplitted);
}
scan.close();
}
}
If you try the sample input above, the output will match the sample output above. However, if you write more than 3 words to the first line and/or more than 2 words to the second line, the userInputSplitFirstLine array of size 3 will store more than 3 words. Same goes with the userInputSplitSecondLine array also. My first question is how can an array of size 3 (userInputSplitFirstLine) and an array of size 2 (userInputSplitSecondLine) can hold more than 3 and 2 elements, respectively? My second question is that how can I restrict/limit the number of words that the user can insert in a line; for example, the first line only accepts 3 words and the second line only accepts 2 words?
Also the answer to this question suggested by Hyperskill.com is as follows:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String wordOne = scanner.next();
String wordTwo = scanner.next();
String wordThree = scanner.next();
String wordFour = scanner.next();
String wordFive = scanner.next();
System.out.println(wordOne);
System.out.println(wordTwo);
System.out.println(wordThree);
System.out.println(wordFour);
System.out.println(wordFive);
}
}
You can use next method of scanner object to read string and then it can be printed easily on new line.
while(true){
if(scanner.hasNext()){
System.out.println(scanner.next());
}
else{
break;
}
}
I think this should do the work. Don't hesitate to ask, if you have some questions.
import java.util.Scanner;
class App {
public static void main(String[] args) {
final StringBuffer line = new StringBuffer();
final StringBuffer words = new StringBuffer();
try (final Scanner sc = new Scanner(System.in)) {
while (sc.hasNextLine()) {
final String currentLine = sc.nextLine();
line.append(currentLine).append(System.lineSeparator());
for (final String word : currentLine.split("\\s+")) {
words.append(word).append(System.lineSeparator());
}
}
} finally {
System.out.println(line.toString());
System.out.println();
System.out.println(words.toString());
}
}
}
My first question is how can an array of size 3 (userInputSplitFirstLine) and an array of size 2 (userInputSplitSecondLine) can hold more than 3 and 2 elements, respectively?
The array here:
String[] userInputSplitFirstLine = new String[3];
is not the same one as the one you got from split:
userInputSplitFirstLine = userInput.split("\\s+");
When you do the above assignment, the old array that was in there is basically "overwritten", and now userInputSplitFirstLine refers to this new array that has a length independent of what the old array had. split always return a new array.
My second question is that how can I restrict/limit the number of words that the user can insert in a line; for example, the first line only accepts 3 words and the second line only accepts 2 words?
It really depends on what you mean by "restrict". If you just want to check if there are exactly three words, and if not, exit the program, you can do this:
userInputSplitFirstLine = userInput.split("\\s+");
if (userInputSplitFirstLine.length != 3) {
System.out.println("Please enter exactly 3 words!");
return;
}
You can do something similar with the second line.
If you want the user to be unable to type more than 3 words, then that's impossible, because this is a command line app.
By the way, the code in the suggested solution works because next() returns the next "word" (or what we generally think of as a word, anyway) by default.
hope this will help you!
public class pratice1 {
public static void main (String[]args) {
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
String input1 = sc.nextLine();
char[]a =input.toCharArray();
char[]a1 = input1.toCharArray();
System.out.println(input +""+ input1);
int a2=0;
if(input!=null) {
for(int i=0;i<input.length();i++) {
if(a[i]==' ') {
a2=i;
for(int j=0;j<a2;j++) {
System.out.println(a[i]);
a2=0;
}
}
else System.out.print(a[i]);
}System.out.println("");
for(int i=0;i<input1.length();i++) {
if(a1[i]==' ') {
a2=i;
for(int j=0;j<a2;j++) {
System.out.println(a1[i]);
a2=0;
}
}
else System.out.print(a1[i]);
}
}
}
}
To solve the problem:
Write a program that reads five words from the standard input and
outputs each word in a new line.
This was my solution:
while(scanner.hasNext()){
System.out.println(scanner.next());
}
We have to make a program on printing initials, which seems pretty easy ok, but I don't know how to cut the string when the input is all on one line using the scanner class in.nextline();. I cant seem to find a way to cut the string using only string methods. Also, another problem arose when I have to also be able to adjust if there isn't a middle name either. if anyone can help me or lead me in the right direction that would be nice.
If you can use split function as you can see below:
String inputString=s.nextLine();
String [] str = inputString.split(" ");
If you want to have extract only first letter then -
import java.util.Scanner;
public class TestStringInput {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Please Enter the Name");
String input = scan.nextLine();
int value = input.indexOf(" ",input.indexOf(" "));
String result = input.substring(0,value);
System.out.println(result);
}
}
But if you want to Extract Starting 2 Initials then change this line-
int value = input.indexOf(" ",input.indexOf(" ")+1);
As Stephen mentioned, your question is about Java, consider re-tagging.
You can use a for loop to iterate through the string. Remember a string is an object. It would help a lot if you posted your code.
import java.util.Scanner;
public class HW03 {
public static void main (String args[])
{
Scanner in = new Scanner(System.in);
String str = "";
System.out.println("What are your first, middle and last names?");
str = in.nextLine();
}
}
I'm trying to do some homework for my computer science class and I can't seem to figure this one out. The question is:
Write a program that reads a line of text and then displays the line, but with the first occurrence of hate changed to love.
This sounded like a basic problem, so I went ahead and wrote this up:
import java.util.Scanner;
public class question {
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a line of text:");
String text = keyboard.next();
System.out.println("I have rephrased that line to read:");
System.out.println(text.replaceFirst("hate", "love"));
}
}
I expect a string input of "I hate you" to read "I love you", but all it outputs is "I". When it detects the first occurrence of the word I'm trying to replace, it removes the rest of the string, unless it's the first word of the string. For instance, if I just input "hate", it will change it to "love". I've looked at many sites and documentations, and I believe I'm following the correct steps. If anyone could explain what I'm doing wrong here so that it does display the full string with the replaced word, that would be fantastic.
Thank you!
Your mistake was on the keyboard.next() call. This reads the first (space-separated) word. You want to use keyboard.nextLine() instead, as that reads a whole line (which is what your input is in this case).
Revised, your code looks like this:
import java.util.Scanner;
public class question {
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a line of text:");
String text = keyboard.nextLine();
System.out.println("I have rephrased that line to read:");
System.out.println(text.replaceFirst("hate", "love"));
}
}
Try getting the whole line like this, instead of just the first token:
String text = keyboard.nextLine();
keyboard.next() only reads the next token.
Use keyboard.nextLine() to read the entire line.
In your current code, if you print the contents of text before the replace you will see that only I has been taken as input.
As an alternate answer, build a while loop and look for the word in question:
import java.util.Scanner;
public class question {
public static void main(String[] args)
{
// Start with the word we want to replace
String findStr = "hate";
// and the word we will replace it with
String replaceStr = "love";
// Need a place to put the response
StringBuilder response = new StringBuilder();
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a line of text:");
System.out.println("<Remember to end the stream with Ctrl-Z>");
String text = null;
while(keyboard.hasNext())
{
// Make sure we have a space between characters
if(text != null)
{
response.append(' ');
}
text = keyboard.next();
if(findStr.compareToIgnoreCase(text)==0)
{
// Found the word so replace it
response.append(replaceStr);
}
else
{
// Otherwise just return what was entered.
response.append(text);
}
}
System.out.println("I have rephrased that line to read:");
System.out.println(response.toString());
}
}
Takes advantage of the Scanner returning one word at a time. The matching will fail if the word is followed by a punctuation mark though. Anyway, this is the answer that popped into my head when I read the question.
I am writing a program where if someone types in the following two lines:
HELLO, I’D LIKE TO ORDER A FZGH
KID’S MEAL
The program will output it like this:
HELLO, I’D LIKE TO ORDER A KID’S MEAL
In other words, the "FZGH" the user inputs into the sentence will be replaced with the second line's words, as you can see: the "FZGH" is replaced by "KID'S MEAL." Kinda get what I mean? If not, I can elaborate more but this is the best I can explain it as.
I'm really close to solving this! My current output is: HELLO, I’D LIKE TO ORDER A FZGH KID’S MEAL
My program didn't replace the "FZGH" with "KID'S MEAL," and I don't know why that is. I thought that by using the .replaceAll() thingy, it would replace "FZGH" with the "KID'S MEAL," but that didn't really happen. Here is my program so far:
public static void main(String[] args) {
sentences();
}
public static void sentences() {
Scanner console = new Scanner(System.in);
String sentence1 = console.nextLine();
String sentence2 = console.nextLine();
//System.out.println(sentence1 + "\n" + sentence2);
String word = sentence1.replaceAll("[FZGH]", "");
word = sentence2;
System.out.print(sentence1 + word);
}
Where did I mess up, resulting in the FZGH still appearing in output?
Use
sentence1 = sentence1.replaceAll("FZGH", "");
String word = sentence2;
Your first (and primary) problem is that you're creating a new String named word, that you're setting to the value of sentence1.replaceAll("[FZGH]", ""). You're then changing the value of word to be sentence2 immediately afterward, so the replacement is lost.
Instead, setting sentence1 to sentence1.replaceAll("FZGH", ""); will change sentence1 to no longer contain the string "FZGH", which is what you're going for. You don't actually need a word value at all, so if you'd like to remove it, it wouldn't hurt.
In addition, using [FZGH] will replace all F's, Z's, G's, and H's from the string- you should use FZGH instead, as this will only remove instances of all four letters in a row.
I think you have a couple of mistakes. Maybe the following is close...
public static void main(String[] args) {
sentences();
}
public static void sentences() {
Scanner console = new Scanner(System.in);
String sentence1 = console.nextLine();
String sentence2 = console.nextLine();
String sentence3 = sentence1+sentence2;
String final = sentence3.replaceAll("FZGH", "");
System.out.print(final);
}
You are reassigning the string "word"
in place of lines :
String word = sentence1.replaceAll("[FZGH]", "");
word = sentence2;
System.out.print(sentence1 + word);
use the following lines
sentence1 = sentence1.replaceAll("[FZGH]", "");
System.out.print(sentence1 + sentence2);
Actually replace method return a string that should be assign again to sentence1. you can run this code its works fine.
public static void main(String[] args) {
sentences();
}
public static void sentences() {
Scanner console = new Scanner(System.in);
String sentence1 = "HELLO, I’D LIKE TO ORDER A FZGH";
String sentence2 = "KID’S MEAL";
//System.out.println(sentence1 + "\n" + sentence2);
sentence1 = sentence1.replace("FZGH", "");
String word = sentence2;
System.out.print(sentence1 + word);
}