Terminating Java User Input While Loop - java

I am learning Java day 1 and I have a very simple code.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
while(input.hasNext()) {
String word = input.next();
System.out.println(word);
}
}
After I input any sentence, the while loop seems to not terminate.
How would I need to change this so that the I could break out of the loop when the sentence is all read?

The hasNext() method always checks if the Scanner has another token in its input. A Scanner breaks its input into tokens using a delimiter pattern that matches whitespace by default.
Whitespace includes not only the space character, but also tab space (\t), line feed (\n), and more other characters
hasNext() checks the input and returns true if it has another non-whitespace character.
Your approach is correct if you want to take input from the console continuously. However, if you just want to have single user input(i.e a sentence or list of words) it is better to read the whole input and then split it accordingly.
eg:-
String str = input.nextLine();
for(String s : str.split(" ")){
System.out.println(s);
}

Well, a simple workaround for this would be to stop whenever you find a stop or any set of strings you would like!
Scanner input = new Scanner(System.in);
while (input.hasNext()) {
String word = input.next();
if (word.equals("stop")) {
break;
}
System.out.println(word);
}
input.close();
System.out.println("THE END!");

Related

String Manipulation - Removing the charachters of the second word to the first word

Enter two words: computer program
result: cute
the character of the second word of the users input is deleted on the first word of the input in java. Leaving "cute"
thought of using replaceAll but could not make it work.
String sentence;
Scanner input = new Scanner(System.in);
System.out.println("Enter 2 words: ");
sentence = input.nextLine();
String[] arrWrd = sentence.split(" ");
String scdWrd = arrWrd[1];
String fnl = arrWrd[0].replaceAll(scdWrd, "");
System.out.println(fnl);
.replaceAll takes a regex, so basically what you are doing here is you're searching for the whole "program" word and replacing it and not its characters, so you just need to add brackets to your scdWrd to let it know that you want to replace the chars:
String scdWrd = "[" + arrWrd[1] + "]";
Just to add to the elegant solution by #B.Mik, you should also check for things like
If multiple spaces are entered between the words.
If the user enters a blank line or just one word e.g. execute your program and enter a blank line or just one word e.g. computer and you will be welcomed with java.lang.ArrayIndexOutOfBoundsException.
The program given below addresses these points:
import java.util.Scanner;
public class LettersFromSecondReplacement {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
boolean valid;
String input;
String words[];
do {
valid = true;
System.out.print("Enter two words separated with space: ");
input = in.nextLine();
words = input.split("\\s+"); //Split on one or more spaces
if (words.length != 2) {
System.out.println("Error: wrong input. Try again");
valid = false;
}
} while (!valid);
for (String s : words[1].split("")) { //Split the 2nd word into strings of one character
words[0] = words[0].replaceAll(s, "");
}
System.out.println(words[0]);
}
}
A sample run:
Enter two words separated with space:
Error: wrong input. Try again
Enter two words separated with space: computer
Error: wrong input. Try again
Enter two words separated with space: computer program
cute
Note that I have used a different algorithm (which you can replace with the one provided by #B.Mik) for replacement. Feel free to comment in case of any doubt/issue
replace line with replaceAll by
String fnl = arrWrd[0];
for (byte c : scdWrd.getBytes()) {
fnl = fnl.replace("" + (char)c, "");
}

Getting a name as an input using regex in java

I am a beginner in both, Java and regular expressions. I want to get a name as an input, by which I mean that only names that have English alphabets A-Z, case insensitive and spaces.
I am using a Scanner class to get my input but my code doesn't work. It looks like:
Scanner sc= new Scanner(System.in);
String n;
while(!sc.hasNext("^[a-zA-Z ]*$"))
{
System.out.println("That's not a name!");
sc.nextLine();
}
n = sc.next();
I checked my regular expression on the website regex101.com and found out that it works fine.
For example, If I input it my name, Akshay Arora , the regex site says it is okay but my program prints
That's not a name
That's not a name
Same line is printed twice and it again asks me for input. Where am I going wrong?
Two parts are wrong:
$ and ^ anchors are considered in the context of entire input, not in the context of the next token. It will never match, unless the input has a single line that matches the pattern in its entirety.
You use default delimiters, which include spaces; therefore, Scanner will never return a token with a space in it.
Here is how you can fix this:
Scanner sc = new Scanner(System.in);
sc.useDelimiter("\n");
String n;
while(!sc.hasNext("[a-zA-Z ]+"))
{
System.out.println("That's not a name!");
sc.nextLine();
}
n = sc.next();
Demo.
Here its sample program related to regex.
public class Program {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String inputName = sc.next();
String regex = "^[a-zA-Z ]*$";
// Compile this pattern.
Pattern pattern = Pattern.compile(regex);
// See if this String matches.
Matcher m = pattern.matcher(inputName);
if (m.matches()) {
System.out.println("Valid Name");
} else
System.out.println("Invalid Name");
}
}
Hope this will help you

Deliminter is not working for scanner

The user will enter a=(number here). I then want it to cut off the a= and retain the number. It works when I use s.next() but of course it makes me enter it two times which I don't want. With s.nextLine() I enter it once and the delimiter does not work. Why is this?
Scanner s = new Scanner(System.in);
s.useDelimiter("a=");
String n = s.nextLine();
System.out.println(n);
Because nextLine() doesn't care about delimiters. The delimiters only affect Scanner when you tell it to return tokens. nextLine() just returns whatever is left on the current line without caring about tokens.
A delimiter is not the way to go here; the purpose of delimiters is to tell the Scanner what can come between tokens, but you're trying to use it for a purpose it wasn't intended for. Instead:
String n = s.nextLine().replaceFirst("^a=","");
This inputs a line, then strips off a= if it appears at the beginning of the string (i.e. it replaces it with the empty string ""). replaceFirst takes a regular expression, and ^ means that it only matches if the a= is at the beginning of the string. This won't check to make sure the user actually entered a=; if you want to check this, your code will need to be a bit more complex, but the key thing here is that you want to use s.nextLine() to return a String, and then do whatever checking and manipulation you need on that String.
Try with StringTokenizer if Scanner#useDelimiter() is not suitable for your case.
Scanner s = new Scanner(System.in);
String n = s.nextLine();
StringTokenizer tokenizer = new StringTokenizer(n, "a=");
while (tokenizer.hasMoreTokens()) {
System.out.println(tokenizer.nextToken());
}
or try with String#split() method
for (String str : n.split("a=")) {
System.out.println(str);
}
input:
a=123a=546a=78a=9
output:
123
546
78
9

Convert a sentence to an array in Java

How can I convert a sentence to an array?
I have this code:
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your sentence: ");
String sentence = scanner.next();
String[] words = sentence.split(" ");
for (String word : words) {
System.out.println(word);
}
But... all this does is just print out the first word of the array and thats it.
Scanner.next()
reads only the next token - not the next line. You want: Scanner.nextLine()
I've added a debugging statement that should make clear a pretty big problem:
import java.util.Scanner;
public class SentenceToWords {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your sentence: ");
String sentence = scanner.next();
//USEFUL INFORMATION!!!
System.out.println("sentence=\"" + sentence + "\"");
String[] words = sentence.split(" ");
for (String word : words) {
System.out.println(word);
}
}
}
Output:
[C:\java_code\]java SentenceToWords
Enter your sentence: setao uhesno uhoesuthesao uh
sentence="setao"
setao
As stated by #Makoto: You're only reading in a word, when you want to read in a line.
next is only literally consuming the next String. Use nextLine instead.
String sentence = scanner.nextLine();
The reason: nextLine() advances the scanner past the newline, which means that it captures the entire line.
It is happening because you are using Scanner, which ignores a string after a space, if you use next(). Use nextLine() instead.

Only one word in println is shown and the rest do not

When I type a phrase into the console, only one word appears below the green text while the other words do not appear. Not sure what I am doing wrong here. Any help would be appreciated.
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a sentence or phrase. It can be anything you want it to be: ");
//ask user for sentence or phrase
String p1 = keyboard.next();
System.out.println(c1); //display user sentence or phrase
next() reads a single word1, use nextLine() to read the entire line.
1 Specifically, 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". The default delimiter is \s+, a continuous string of whitespace characters. You can change this delimiter via useDelimiter.
Change your code to this:
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a sentence or phrase. It can be anything you want it to be: ");
//ask user for sentence or phrase
String p1 = keyboard.nextLine();
System.out.println(c1); //display user sentence or phrase
The problem is
keyboard.next();
only gets a single word. You need to use:
keyboard.nextLine();

Categories