How to input a specific number of words in java? - java

I'm supposed to input an array of strings in java according to the following specification:
Input:A text containing K English words (where K <= 5000), with spaces and punctuation marks
My approach is to use an array of strings, each string containing a word and taking input using java.util.Scanner.next() inside a loop.
My problem is how to stop taking inputs when the user hits enter. Any idea?

Use a Scanner. Read the lines that the user enters. If the user enters an empty line then exit the loop:
public static void main(String[] args) throws Exception {
final Scanner scanner = new Scanner(System.in);
while (true) {
final String read = scanner.nextLine();
if ("".equals(read)) {
break;
}
System.out.println(read);
}
}

You could use two Scanner objects to handle this like so:
Scanner inScan = new Scanner(System.in);
String line = sinScan.nextLine();
while (line.length() > 0) {
Scanner lineScan = new Scanner(line);
while(lineScan.hasNext()) {
String word = lineScan.next();
// process this word.
}
line = inScan.nextLine();
}
// loop should exit when the user enters a blank line.

Related

java.util.NoSuchElementException: No line found ; error when I have a new variable each time for input [duplicate]

This question already has answers here:
java.util.NoSuchElementException - Scanner reading user input
(5 answers)
Closed 3 years ago.
I'm trying to run my program in a loop and it runs perfectly fine the first time, but once it loops over and tries to find the nextLine, it crashes.
My only issue with this is that I have a variable that is assigned by scanner.nextLine() then it delimits it. Shouldn't it ask for input every time instead of erroring?
private static List<String> readInput()
{
ArrayList<String> inputtedWords = new ArrayList<String>(); // creates an ArrayList called inputtedWords
Scanner kb = new Scanner(System.in); //creating a scanner kb (keyboard)
System.out.println("Text: "); // user input for Text:
String fullText = kb.nextLine();
Scanner s = new Scanner(fullText).useDelimiter(" "); //parses the fullText string and separates them on spaces
while(s.hasNext()) // loops until their is not another word
{
String tempStr = s.next();
if (!Character.isAlphabetic(tempStr.charAt(tempStr.length()-1)))
tempStr = tempStr.substring(0, tempStr.length()-1);
inputtedWords.add(tempStr);
}
s.close();//closing scanners
kb.close();//closing scanners
return inputtedWords; // returns the inputtedWords list
}
This is the code for the beginning of the loop...
List<String> dictionary = readDictionary(); // creates a List called dictionary and sets it equal to the file in method "readDictionary"
while (done) // Change this to a while loop and negate it. Remember to get another line of input at the end of the loop.
{
List<String> inputtedWords = readInput(); // creates another List for the words inputted into the method "readInput"
if ((inputtedWords.size() == 1) && (inputtedWords.get(0).equals("done")))
{
done = false;
System.out.println("Exiting Program");
continue;
}
for (String newWord : inputtedWords) // newWord = word inputted
{ // beginning of for loop, initializes element as a string then searches loops through the length of inputtedWords
List<String> possibleAnswers = new ArrayList<>(); //creates an ArrayList called "possibleAnswers"
possibleAnswers.add(newWord); // adds the newly created word into the possibleAnswers list
List<String> characters = new ArrayList<String>(); // creates another ArrayList called "chars"
I've been working on a fix for this for a while but cannot seem to figure out why it's erroring on me.
On you code,
private static List<String> readInput(){
//Your other code here
Scanner kb = new Scannr(System.in); //creating a scanner kb (keyboard)
//Your other code here
String fullText = kb.nextLine(); // read from user input
//Your other code here
}
this Error was encountered due to the loop here
while (done){
List<String> inputtedWords = readInput();
//Your other code here
}
base on Oracle documentation for Java here. And I quote:
public String nextLine()
Advances this scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line.
Since this method continues to search through the input looking for a line separator, it may buffer all of the input searching for the line to skip if no line separators are present.
Returns:
the line that was skipped
Throws:
NoSuchElementException - if no line was found
It is recommended to add kb.hasNextLine() as validation to avoid the exception.
private static List<String> readInput(){
//Your other code here
Scanner kb = new Scannr(System.in); //creating a scanner kb (keyboard)
//Your other code here
String fullText = kb.hasNextLine() ? kb.nextLine() :""; // read from user input with validation
//Or you can use. Use only one of these codes.
String fullText = ""; // read from user input with validation
if(kb.hasNextLine()){
fullText = kb.nextLine();
}
//Your other code here
}
But you might get an infinite loop from that code.
You can solve the infinite loop by moving the variable of kb into static class attribute like
private static Scanner kb = null;
private static List<String> readInput(){
//Your other code here
//kb = new Scannr(System.in); creating a scanner kb (keyboard) ***REMOVE this line***
Scanner s = new Scanner(fullText).useDelimiter(" "); //parses the fullText string and separates them on spaces. ***This should be fine to where it is.****
//Your other code here
String fullText = kb.nextLine(); // read from user input
//Your other code here
s.close();//closing scanners ***This should be fine to where it is.****
//kb.close(); closing scanners ***REMOVE this from here***
}
Then move innitialization of scanner and kb.close(); outside your loop. like:
kb = new Scannr(System.in);
while (done){
List<String> inputtedWords = readInput();
//Your other code here
}
kb.close(); closing scanner
If you don't want scanner as static attribute of the class, you can just send scanner as argument of the method like:
private static List<String> readInput(Scanner kb){
//Your other code here
String fullText = kb.hasNextLine() ? kb.nextLine() :""; // read from user input with validation
//Your other code here
}
On your loop
Scanner kb = new Scannr(System.in);
while (done){
List<String> inputtedWords = readInput(kb);
//Your other code here
}
kb.close(); closing scanner
Moving the kb.close() outside of the loop fixed the whole thing.

How to limit the number of words when reading a line from standard input?

I am new to Stackoverflow and this is my first time asking a question. I have searched my problem thoroughly, however, could not find an appropriate answer. I am sorry if this has been asked. Thank you in advance.
The question is from Hyperskill.com as follows:
Write a program that reads five words from the standard input and outputs each word in a new line.
First, you need to print all the words from the first line, then from the second (from the left to right).
Sample Input 1:
This Java course
is adaptive
Sample Output 1:
This
Java
course
is
adaptive
My trial to solve it
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
/* I have not initialized the "userInput" String.
* I know that String is immutable in Java and
* if I initialize it to an empty String ""
* and read a String from user.
* It will not overwrite to the "userInput" String.
* But create another String object to give it the value of the user input,
* and references the new String object to "userInput".
* I didn't want to waste memory like that.
*/
String userInput;
String[] userInputSplitFirstLine = new String[3];
String[] userInputSplitSecondLine = new String[2];
Scanner scan = new Scanner(System.in);
userInput = scan.nextLine();
userInputSplitFirstLine = userInput.split("\\s+");
userInput = scan.nextLine();
userInputSplitSecondLine = userInput.split("\\s+");
for(String firstLineSplitted: userInputSplitFirstLine) {
System.out.println(firstLineSplitted);
}
for(String secondLineSplitted: userInputSplitSecondLine) {
System.out.println(secondLineSplitted);
}
scan.close();
}
}
If you try the sample input above, the output will match the sample output above. However, if you write more than 3 words to the first line and/or more than 2 words to the second line, the userInputSplitFirstLine array of size 3 will store more than 3 words. Same goes with the userInputSplitSecondLine array also. My first question is how can an array of size 3 (userInputSplitFirstLine) and an array of size 2 (userInputSplitSecondLine) can hold more than 3 and 2 elements, respectively? My second question is that how can I restrict/limit the number of words that the user can insert in a line; for example, the first line only accepts 3 words and the second line only accepts 2 words?
Also the answer to this question suggested by Hyperskill.com is as follows:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String wordOne = scanner.next();
String wordTwo = scanner.next();
String wordThree = scanner.next();
String wordFour = scanner.next();
String wordFive = scanner.next();
System.out.println(wordOne);
System.out.println(wordTwo);
System.out.println(wordThree);
System.out.println(wordFour);
System.out.println(wordFive);
}
}
You can use next method of scanner object to read string and then it can be printed easily on new line.
while(true){
if(scanner.hasNext()){
System.out.println(scanner.next());
}
else{
break;
}
}
I think this should do the work. Don't hesitate to ask, if you have some questions.
import java.util.Scanner;
class App {
public static void main(String[] args) {
final StringBuffer line = new StringBuffer();
final StringBuffer words = new StringBuffer();
try (final Scanner sc = new Scanner(System.in)) {
while (sc.hasNextLine()) {
final String currentLine = sc.nextLine();
line.append(currentLine).append(System.lineSeparator());
for (final String word : currentLine.split("\\s+")) {
words.append(word).append(System.lineSeparator());
}
}
} finally {
System.out.println(line.toString());
System.out.println();
System.out.println(words.toString());
}
}
}
My first question is how can an array of size 3 (userInputSplitFirstLine) and an array of size 2 (userInputSplitSecondLine) can hold more than 3 and 2 elements, respectively?
The array here:
String[] userInputSplitFirstLine = new String[3];
is not the same one as the one you got from split:
userInputSplitFirstLine = userInput.split("\\s+");
When you do the above assignment, the old array that was in there is basically "overwritten", and now userInputSplitFirstLine refers to this new array that has a length independent of what the old array had. split always return a new array.
My second question is that how can I restrict/limit the number of words that the user can insert in a line; for example, the first line only accepts 3 words and the second line only accepts 2 words?
It really depends on what you mean by "restrict". If you just want to check if there are exactly three words, and if not, exit the program, you can do this:
userInputSplitFirstLine = userInput.split("\\s+");
if (userInputSplitFirstLine.length != 3) {
System.out.println("Please enter exactly 3 words!");
return;
}
You can do something similar with the second line.
If you want the user to be unable to type more than 3 words, then that's impossible, because this is a command line app.
By the way, the code in the suggested solution works because next() returns the next "word" (or what we generally think of as a word, anyway) by default.
hope this will help you!
public class pratice1 {
public static void main (String[]args) {
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
String input1 = sc.nextLine();
char[]a =input.toCharArray();
char[]a1 = input1.toCharArray();
System.out.println(input +""+ input1);
int a2=0;
if(input!=null) {
for(int i=0;i<input.length();i++) {
if(a[i]==' ') {
a2=i;
for(int j=0;j<a2;j++) {
System.out.println(a[i]);
a2=0;
}
}
else System.out.print(a[i]);
}System.out.println("");
for(int i=0;i<input1.length();i++) {
if(a1[i]==' ') {
a2=i;
for(int j=0;j<a2;j++) {
System.out.println(a1[i]);
a2=0;
}
}
else System.out.print(a1[i]);
}
}
}
}
To solve the problem:
Write a program that reads five words from the standard input and
outputs each word in a new line.
This was my solution:
while(scanner.hasNext()){
System.out.println(scanner.next());
}

How to skip whitespaces and take input in Single line using Scanner

I need to take input in a single line of String which is a combination of String and integers.
I have tried to take the input like this
Scanner in = new Scanner(System.in);
String stringWithoutSpaces=in.nextLine();
But, scanner reads only the first character.
Input String:A 10,B 10,C 10,D 10
Required String:A10,B10,C10,D10
I need this input in a one single line using scanner class.
From what I understand, you are trying to receive the string from the user without storing all the white spaces. If your goal is to remove all the white spaces from the user input string, you can use replaceAll.
Code:
Scanner in = new Scanner(System.in);
System.out.print("Enter input: ");
String input = in.nextLine();
String noWhiteSpaces = input.replaceAll(" ", "");
System.out.println(noWhiteSpaces);
Console:
Enter input: A 10,B 10,C 10,D 10
A10,B10,C10,D10
import java.util.*;
public class Solution {
public static void main(String args[]) {
System.out.println("Hello world");
Scanner scanner=new Scanner(System.in);
String aItems = scanner.nextLine();
System.out.println(aItems);
}
}
This is working fine. I have Provided same input as mentioned by you and it is taking it as one string.Share your complete code or match from this one.

Java String - How to get chars until and after space

I'm load to variable string using:
Scanner scanner = new Scanner(System.in);
x = scanner.nextLine();
String always looks like: "Random Example". I want to grab first word (before space) for one variable and second word (after space) to next one variable. Can someone show me example?
You can get split a String using .split(String s) and put it in a String[]
String editMe;
Scanner user_input = new Scanner( System.in );
editMe = user_input.nextLine();
String[] edit1 = editMe.split(" ");
If you would like to see the values in the System you can use
int i =0;
for(String s:edit1)
{
System.out.println(s);
i++;
}
See more information on the String variable and how to use it here.
Input obtained from scanning the input stream can be split based on the space character.
Scanner scanner = new Scanner(System.in);
String x = scanner.nextLine();
String array[] =x.split(" ");
In this way, the words are stored in array.

issue with exit condition of loop?

I am trying to use a while condition where if a user inputs a string with the first character as number 1, the loop should end. However, in my case the loop never ends. What could I be doing wrong?
public static void main(String[] args) {
ArrayList<Integer> instructions = new ArrayList<Integer>();
Scanner keyboard = new Scanner(System.in);
String input = "";
String termIns = input.substring(0);
// int termInsInt= Integer.parseInt(termIns);
do {
input = keyboard.nextLine();
int inputInt = Integer.parseInt(input);
instructions.add(inputInt);
//String termIns = input.substring(0);
} while(!termIns.equals("1"));
In addition, what would display the list of all elements in the ArrayList?
You need to update termIns with the user input in each iteration of loop:
do {
input = keyboard.nextLine();
int inputInt = Integer.parseInt(input);
instructions.add(inputInt);
termIns = input.substring(0);
} while(!termIns.equals("1"));
Also substring(0) will not help you as
substring(int beginIndex)
Returns a new string that is a substring of
this string. The substring begins with the character at the specified
index and extends to the end of this string.
You can use startsWith method instead directly on input as mentioned here
while(!input.startsWith("1"))
you're not updating termsIn which is part of your terminating condition.
Also, you can display all the elements in the Arraylist by creating a loop outside of your do-while that prints out all the elements in your arraylist. I'd take a look at the javadoc on Arraylist.

Categories