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);
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 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
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);
}
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();
I have 2 inputs from user. One is say greetings and the other one is tell me your name
But when I write after something hello, ex: Hello mate!! Scanner does not read the second input which is mate and takes hello from first string second one is also same
any advice
Thanks
public static void main(String[] args) {
System.out.println("Choose what would you like to say ?");
String str1 = "";
String str2 = "";
System.out.println("Say any greetings word");
str1 = input();
System.out.println("Tell me your name");
str2 = input();
if (str2.equalsIgnoreCase("zia")) {
System.out.println("Hello Mr Zia, What a nice suprise");
}
else {
System.out.println(str1 + " " + str2);
}
}
public static String input() {
Scanner sc = new Scanner(System.in);
return sc.next();
}
First of all, you need sc.nextLine() to read the whole input.
Second, you shouldn't create a new scanner every time. Just re-use the scanner like this:
Scanner sc = new Scanner(System.in);
System.out.println("Say any greetings word");
str1 = sc.nextLine();
System.out.println("Tell me your name");
str2 = sc.nextLine();
And close the scanner if you don't need it any more:
sc.close();
That way you don't even need the input()-method any more.
You cannot build more than one Scanner on the same input stream. They will conflict with each other, leading to the inconsistencies you're observing.
With your program as shown every call to the method input() will build a new Scanner on the one unique System.in. That's more than one Scanner on the same input stream. Won't work.
Instead, build one Scanner once and for all, at the very beginning of your program, and use that one unique Scanner every time you need to read input.
Like this:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Choose what would you like to say ?");
System.out.println("Say any greetings word");
String greeting = scanner.next();
System.out.println("Tell me your name");
String name = scanner.next();
if (name.equalsIgnoreCase("zia")) {
System.out.println("Hello Mr Zia, What a nice suprise");
} else {
System.out.println(greeting + " " + name);
}
}