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
Related
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));
}
}
I'm trying to write a scanner so that every time \n is detected, it will scan the line after that until a new \n shows up. I first tried something like this.
import java.util.Scanner;
public class test{
public static void main(String[] args) {
String input = "first line \nsecond line \nthird line";
Scanner sc = new Scanner(input);
while(sc.hasNextLine()) {
String stuff = sc.nextLine();
System.out.println(stuff);
}
sc.close();
}
}
Which works, and the output is
first line
second line
third line
However, when I try doing the same thing with Scanner(System.in) it doesn't work the same way even with same input
import java.util.Scanner;
public class test{
public static void main(String[] args) {
System.out.println("Please enter things");
Scanner cmd = new Scanner(System.in); //input: "first \n second \n third"
String input = cmd.nextLine();
Scanner sc = new Scanner(input);
while(sc.hasNextLine()) {
String stuff = sc.nextLine();
System.out.println(stuff);
}
cmd.close();
sc.close();
}
}
Output:
first \n second \n third
What should I change, so that every \n will print a new line?
EDIT:
If the input was
first
second
third
and entered into the prompt at once, would scanner.nextLine() be enough to suffice?
System.out.println("Please enter things");
Scanner cmd = new Scanner(System.in); //input: "first \n second \n third"
while(cmd.hasNext()) {
String word = cmd.next();
if(word.equals("\\n")) {
System.out.println();
}else {
System.out.print(word);
}
}
In all honesty, you will need to utilize these sub-strings at some point outside of your while loop so it would actually be better to split the line based on the same delimiter and have each substring as a element within a String Array This way you don't need to utilize Scanner and a while loop for this at all, for example:
String input = "first line \n second line \n third line"; // Read in data file line...
String[] stuffArray = input.split("\\s+?\n\\s+?");
System.out.println(Arrays.toString(stuffArray));
System.out.println();
System.out.println(" OR in other words");
System.out.println();
for(String str : stuffArray) {
System.out.println(str);
}
If you want to do this using System.in:
Scanner sc = new Scanner(System.in);
System.out.println("Enter text:");
String stuff = sc.nextLine();
String[] subArray = stuff.trim().split("(\\s+)?(\\\\n)(\\s+)?");
System.out.println();
// Display substrings...
for (String strg : subArray) {
System.out.println(strg);
}
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'm pretty much a complete newbie when it comes to Java. I've dabbled a bit in python and VB.net, and that's about it.
I'm trying to write a program in java that literally reads the user's input and displays it back to them with this code:
import java.util.Scanner;
public class InputTesting
{
public static void main( String[] args )
{
Scanner input = new Scanner ( System.in );
String str1;
System.out.println("Input string: ");
str1 = input.nextString();
System.out.println( str1 );
}
}
And I get the error:
InputTesting.java:13: error: cannot find symbol
str1 = input.nextString();
^
symbol: method nextString()
location: variable input of type Scanner
1 error
Can someone tell what why it's not compiling? Thanks!
input.nextString();
There is no method called nextString in the Scanner class. That's why you're getting the error cannot find symbol.
Try
input.nextLine(); // If you're expecting the user to hit enter when done.
input.next(); // Just another option.
import java.util.Scanner;
public class InputTesting
{
public static void main( String[] args )
{
Scanner input = new Scanner ( System.in );
String str1;
System.out.println("Input string: ");
str1 = input.next();
System.out.println( str1 );
}
}
You may use one of input.nextXXX() as detailed in Scanner javadoc. to resolve compiler error
in your case
you may use input.nextLine(); get entire line of text.
By Default whitespace delimiter used by a scanner. However If you need to scan sequence of inputs separated by a delimiter useDelimiter can be used to set regex delim
public static void main(String[] args) {
try (Scanner input = new Scanner(System.in);) {
input.useDelimiter(";");
while (input.hasNext()) {
String next = input.next();
if ("DONE".equals(next)) {
break;
}
System.out.println("Token:" + next);
}
}
}
Input
1a;2b;3c;4d;5e;DONE;
Output
Token:1a
Token:2b
Token:3c
Token:4d
Token:5e
Just be cautious while scanning decimal and signed numbers as scanning is Locale Dependent
You need to rather use method nextLine(). This methods prints entire line. By using next() it will print only one word in your sentence.
// That's how i managed solution for input a string
import java.util.Scanner;
public class PalindromeWord {
public static void main(String[] args) {
//System.out.println("Enter a string: ");
Scanner input = new Scanner(System.in);
String S = input.next();
String reverseStr = "";
int strLength = S.length();
for (int i = (strLength - 1); i >=0; --i) {
reverseStr = reverseStr + S.charAt(i);
}
if (S.equals(reverseStr)) {
System.out.println("Yes");
}
else {
System.out.println("No");
}
}
}