Writing Recursive Method ; Reverse Word - java

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();

Related

How do I use the replaceAll() function recursively?

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));
}
}

Reverse sentence duplicate removal

I need to remove "the enter a sentence to be reversed" bit at the top and the bottom, because it shouldn't be there. Below is my code and the console message that needs to be fixed.
import java.util.Scanner;
public class ques1 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String sentence;
do {
String newsent = "";
System.out.println("\nEnter a sentence to be reversed: ");
sentence = scanner.nextLine();
for (int i = sentence.length() - 1; i >= 0; i--) {
newsent = newsent + sentence.charAt(i);
}
System.out.print(newsent);
} while (!sentence.equals("exit"));
}
}
Enter a sentence to be reversed: (want to remove this)
Enter a sentence to be reversed:
Hi how are you?
?uoy era woh iH
Enter a sentence to be reversed:
I am doing great, thanks.
.sknaht ,taerg gniod ma I
Enter a sentence to be reversed:
Exit
tix
Enter a sentence to be reversed: (Want to remove this)
Your input is wrong and it doesn't match with the string check "exit". The loop will continue till you feed the input as "exit".

parsing Strings in java

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);

Java string to array and replace a certain word from user to uppercase

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

Comparing a string outside a loop with one outside the loop in java

I am working on writing a program that takes a word from the user like "banana" takes the first letter of the word "b" puts it at the end like ananab then checks to see if it spells the same word. I have been working on this for a couple days and have tried several things but still unsure about how to check a string given by the user with one inside a for loop. This is my program so far.
public static void main(String[] args) {
System.out.println("Enter words that can be checked for backward spelling");
System.out.println("Please enter a word to check");
Scanner keyboard = new Scanner(System.in);
String words = keyboard.nextLine();
String firstLetter = String.valueOf(words.charAt(0));
String words2 = words.substring(1);
String otherwords = words2+firstLetter;
for (int i=otherwords.length()-1; i>=0; i--){
String newwords=String.valueOf(otherwords.charAt(i));
boolean match = newwords.equalsIgnoreCase(words);
if (match){
System.out.println("This word matches the criteria we are lookin for");}
}
}
}
public static void main(String []args){
String input = new Scanner(System.in).nextLine();
char addToEnd = input.charAt(0);
String newString = input.substring(1);
newString+=addToEnd;
if(input.equals(newString)){
System.out.println("This is a match");
}
Try this:
public static void main(String[] args) {
System.out.println("Enter words that can be checked for backward spelling");
System.out.println("Please enter a word to check");
Scanner sc = new Scanner(System.in);
String word = sc.nextLine();
StringBuilder sb = new StringBuilder();
sb.append(word.substring(1));
sb.append(word.charAt(0));
System.out.println(sb.toString().equals(word)?"This is a match.":"This is not a match.");
}
System.out.println("Enter words that can be checked for backward spelling");
System.out.println("Please enter a word to check");
Scanner keyboard = new Scanner(System.in);
String word = keyboard.nextLine();
keyboard.close();
String firstLetter = word.substring(0, 1);
String newWord = word.substring(1) + firstLetter;
// reverse the word
String reversedWord = "";
for (int i = 0; i < word.length(); i++) {
reversedWord = word.substring(i, i + 1) + reversedWord;
}
// check if it matches
if (reversedWord.equalsIgnoreCase(newWord)) {
System.out.println("This word matches the criteria we are looking for!!!");
}

Categories