The program should allow a user to enter a string, a substring they wish to find and
another string with which they wish to replace the found substring.
The output of your program should be similar to the output given below:
Please enter a string: Hello world
Please enter the substring you wish to find: llo
Please enter a string to replace the given substring: ##
Your new string is: he## world
I am new to Java and cant find and so far this is what I have:
import java.util.Scanner;
public class searchReplace
{
static String word, substring, newWord;
static String output = "";
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Please enter a string: ");
word = input.next();
System.out.println("Please enter the substring you wish to find: ");
substring = input.next();
System.out.println("Please enter a string to replace the given substring: ");
newWord = input.next();
replace(substring,newWord);
input.close();
}
private static void replace(String substring, String newWord)
{
if(output.contains(newWord))
{
System.out.println(output);
}
else
{
output = word.replaceAll("substring","newWord");
replace(substring,newWord);
}
}
}
I Get The Error:
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.contains(java.lang.CharSequence)" because "searchReplace.output" is null
at searchReplace.replace(searchReplace.java:33)
at searchReplace.main(searchReplace.java:21)
For your goal, you need to use just:
output = word.replace(substring, newWord);
instead of:
word.replaceAll("substring", "newWord");
You don't need to make any recursion. Replace function will replace your substring inside word with the newWord for each occurence.
Recursion is not needed:
public static void main(String [] args) {
try (Scanner scanner = new Scanner(System.in)) {
System.out.println("Enter String: ");
String input = scanner.nextLine();
System.out.println("String to replace: ");
String toReplace = scanner.nextLine();
System.out.println("Replace with: ");
String replaceWith = scanner.nextLine();
System.out.println(input.replaceAll(toReplace, replaceWith));
}
}
Related
i have figured out a way to replace vowels into * but it only converts the first line
input:
break
robert
yeah
output:
br**k
here is the code
public class Solution {
public static void main(String[] args) {
String enterWord;
Scanner scan = new Scanner (System.in);
enterWord = scan.nextLine();
enterWord = enterWord.replaceAll("[aeiou]", "*");
System.out.println(enterWord);
}
}
is there any way that it reads all three words?
Your code works as you want (in:break robert yeah out: br**k r*b*rt y**h) on my env(Windows10, java1.8.0_271), maybe you can set a breakpoint on enterWord = enterWord.replaceAll("[aeiou]", "*"); and check is the enterWord recived whole input string.
You need a loop to keep getting and processing the inputs. Also, I suggest you use (?i) with the regex to make it case-insensitive.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
String enterWord, answer = "y";
Scanner scan = new Scanner(System.in);
do {
System.out.print("Enter a word: ");
enterWord = scan.nextLine();
enterWord = enterWord.replaceAll("(?i)[aeiou]", "*");
System.out.println("After replacing vowels with * it becomes " + enterWord);
System.out.print("Do you wish to conntinue[y/n]: ");
answer = scan.nextLine();
} while (answer.equalsIgnoreCase("y"));
}
}
A sample run:
Enter a word: hello
After replacing vowels with * it becomes h*ll*
Do you wish to conntinue[y/n]: y
Enter a word: India
After replacing vowels with * it becomes *nd**
Do you wish to conntinue[y/n]: n
For a single string spanning multiple lines, the method, String#replaceAll works for the entire string as shown below:
public class Main {
public static void main(String[] args) {
String str = "break\n" +
"robert\n" +
"yeah";
System.out.println(str.replaceAll("(?i)[aeiou]", "*"));
}
}
Output:
br**k
r*b*rt
y**h
Using this feature, you can build a string of multiple lines interactively and finally change all the vowels to *.
Demo:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
String text = "";
Scanner scan = new Scanner(System.in);
StringBuilder sb = new StringBuilder();
System.out.println("Keep enter some text (Press Enter without any text to stop): ");
while (true) {
text = scan.nextLine();
if (text.length() > 0) {
sb.append(text).append(System.lineSeparator());
} else {
break;
}
}
System.out.println("Your input: \n" + sb);
String str = sb.toString().replaceAll("(?i)[aeiou]", "*");
System.out.println("After converting each vowel to *, your input becomes: \n" + str);
}
}
A sample run:
Keep enter some text (Press Enter without any text to stop):
break
robert
yeah
Your input:
break
robert
yeah
After converting each vowel to *, your input becomes:
br**k
r*b*rt
y**h
create a java program that will ask a user to input a word and reverse it using the recursive method. It should ask the user to try again y or n
I have missing code I don't know what should I put on line 14.
package reverseword;
import java.util.Scanner;
public class ReverseWord {
public static void main(String[] args) {
String tryAgain = "Y";
do{
String reversedString = "";
System.out.print("Enter string to reversed: ");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
reversedString = reverseString(input);
System.out.println("Reversed String : "+reversedString);
System.out.println("Try again? enter \"Y/N\": ");
tryAgain = input.next();
}while(!tryAgain.equals("N"));
}
public static String reverseString(String input){
if(input.isEmpty())
return input;
return reverseString(input.substring(1)) + input.charAt(0);
}
}
Enter string to reversed:lala
Reversed String : alal
Try again? enter \"Y/N\": Y
Enter string to reversed:
//if the answer is no:
Enter string to reversed:lala
Reversed String : alal
Try again? enter \"Y/N\": N
Bye!
I assume that 14th line is
tryAgain = input.next();
It does not compile because input is String, you meant to use Scanner sc. Try this:
tryAgain = sc.next();
The same question was asked before but I the help wasn't sufficient enough for me to get it solved. When I run the program many times, it goes well for a string with comma in between(e.g. Washington,DC ). For a string without comma(e.g. Washington DC) the program is expected to print an error message to the screen and prompt the user to enter the correct input again. Yes, it does for the first run. However, on the second and so run, it fails and my suspect is on the while loop.
Console snapshot:
Enter input string:
Washington DC =>first time entered & printed the following two lines
Error: No comma in string.
Enter input string:
Washington DC => second time, no printouts following i.e failed
Here's my attempt seeking your help.
public class practice {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String userInput = "";
String delimit =",";
boolean inputString = false;
System.out.println("Enter input string:");
userInput = scnr.nextLine();
while (!inputString) {
if (userInput.contains(delimit)){
String[] userArray = userInput.split(delimit);
// for(int i=0; i<userArray.length-1; i++){
System.out.println("First word: " + userArray[0]); //space
System.out.println("Second word:" + userArray[1]);
System.out.println();
//}
}
else if (!userInput.contains(delimit)){
System.out.println("Error: No comma in string.");
inputString= true;
}
System.out.println("Enter input string:");
userInput = scnr.nextLine();
while(inputString);
}
}
}
You can easily solve this problem using a simple regex ^[A-Z][A-Za-z]+, [A-Z][A-Za-z]+$
So you can check the input using :
boolean check = str.matches("^[A-Z][A-Za-z]+, [A-Z][A-Za-z]+$");
Then you can use do{}while() loop instead, so your code should look like this :
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String userInput;
do {
System.out.println("Enter input string:");
userInput = scnr.nextLine();
} while (!userInput.matches("^[A-Z][A-Za-z]+, [A-Z][A-Za-z]+$"));
}
regex demo
Solution 2
...But I can't apply regex at this time and I wish others help me to
finish up the work the way I set it up
In this case you can use do{}while(); like this :
Scanner scnr = new Scanner(System.in);
String userInput;
String delimit = ",";
boolean inputString = false;
do {
System.out.println("Enter input string:");
userInput = scnr.nextLine();
if (userInput.contains(delimit)) {
String[] userArray = userInput.split(delimit);
System.out.println("First word: " + userArray[0]);
System.out.println("Second word:" + userArray[1]);
System.out.println();
} else if (!userInput.contains(delimit)) {
System.out.println("Error: No comma in string.");
inputString = true;
}
} while (inputString);
Here is the full Question:
...
My Code
import java.util.Scanner;
import java.lang.StringBuilder;
public class javaAPIString {
public static void main(String[]args)
{
String SentenceFromUser = "";
String IndiWordFromUser = "";
/// String upper = IndiWordFromUser.toUpperCase();
//String[] words = SentenceFromUser.split("\\s+");
char ans;
Scanner keyboard = new Scanner(System.in);
do
{
final StringBuilder result = new StringBuilder(SentenceFromUser.length());
String[] words = SentenceFromUser.split("\\s");
System.out.println("Enter a sentence :");
SentenceFromUser = keyboard.nextLine();
System.out.println("Enter a word : ");
IndiWordFromUser = keyboard.next();
/// IndiWordFromUser = upper;
for(int i =0; i > words.length; i++ )
{
if (i > 0){
result.append(" ");
}
result.append(Character.toUpperCase(words[i].charAt(0))).append(
words[i].substring(1));
}
// System.out.println("The Output is : " + SentenceFromUser);
System.out.println("Do you want to enter another sentence and word ? If yes please type 'Y' or 'y'.");
ans = keyboard.next().charAt(0);
}
while ((ans == 'Y') || (ans == 'Y'));
}
}
My Output/ problem of my code :
Enter a sentence :
i like cookies
Enter a word :
cookies
The Output is : i like cookies
Do you want to enter another sentence and word ? If yes please type 'Y' or 'y'.
it returns the same original sentence without changing to Uppercase of the second input to replace to all CAPS.
I hope my solution will help you out! :)
import java.util.Scanner;
public class Solution {
private static Scanner in = new Scanner(System.in);
public static void main(String[] args) {
getTextFromUser();
}
private static void getTextFromUser() {
print("Enter Sentence Here: ");
String text = in.nextLine();
print("\nDo you want to capitalize words in sentence? Y/N: ");
while (in.nextLine().equalsIgnoreCase("y")) {
print("Enter Word: ");
print("Modified Text: " + changeWord(text, in.nextLine()));
print("\n\nDo you want to capitalize words in sentence? Y/N");
}
}
private static String changeWord(String text, String word) {
return text.replaceAll("\\b" + word + "\\b" /* \\b Means word
boundary */, word.toUpperCase()); // No validations done.
}
private static void print(String message) {
System.out.print(message);
}
}
Just some things:
please use java naming conventions for variables name
when you execute your code this instruction will overwrite the user input with an empty string.
IndiWordFromUser = upper;
String[] words = SentenceFromUser.split("\\s");... you are splitting an empty string the first time and the old sentence the other runs
The variable IndiWordFromUser is never read
I was solving HackerRank "30 Days Of Code" problem 8.
This is the code I wrote:
import java.util.*;
import java.io.*;
public class Directory
{
public static void main(String args[])throws NoSuchElementException
{
Scanner sc=new Scanner(System.in);
//System.out.println("Enter number");
int n=sc.nextInt();
sc.nextLine();
Map<String,String> Directory= new HashMap<String,String>();
for (int i=0;i<n;i++)
{
//System.out.println("Enter name and phone number");
String name=sc.next();
String ph=sc.next();
sc.nextLine();
Directory.put(name,ph);
}
while(sc.hasNext())
{
String s = sc.next();
sc.nextLine();
String phoneNumber = Directory.get(s);
System.out.println((phoneNumber != null) ? s + "=" + phoneNumber : "Not found");
}
}
}
When I run this code with the custom input I get an error as follows:
Exception in thread "main" java.util.NoSuchElementException: No line
found at java.util.Scanner.nextLine(Scanner.java:1585) at
Directory.main(Directory.java:23)
I think this is occurring due to the "sc.nextLine()" in the while loop. But I'm not able to figure out why. I had learnt from here that I should use sc.nextLine() after using sc.next() so that the control is transferred to the next line of input. Any ideas where I am going wrong?
From Documentation:
public String next() Finds and returns the next complete token from
this scanner. A complete token is preceded and followed by input that
matches the delimiter pattern
And also from the Documentation of Scanner:
A Scanner breaks its input into tokens using a delimiter pattern,
which by default matches whitespace
And whitespace includes \n and \r.
So as a conclusion, using nextLine() to workaround the newline problem is valid in case of nextInt() but it is not in case of using next().
I think this will work for you. Try it :)
You do not need this line sc.nextLine();
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter number");
int n=sc.nextInt();
Map<String,String> directory= new HashMap<>();
for (int i=0;i<n;i++)
{
System.out.println("Enter name and phone number");
String name=sc.next();
String ph=sc.next();
sc.nextLine();
directory.put(name,ph);
}
while(sc.hasNext())
{
String s = sc.next();
sc.nextLine();
String phoneNumber = directory.get(s);
System.out.println((phoneNumber != null) ? s + "=" + phoneNumber : "Not found");
}
}