How to take multi-line input in Java - java

I'm trying to take multi-line user input in Java and split the lines into an array, I need this to solve a problem for an online judge. I'm using a Scanner to take input. I cant determine the end of input. I always get an infinite loop, since I don't know the size of input (i.e number of lines)
Terminating input with an empty String (clicking enter) is still an infinite loop. Code provided below.
public static void main(String[] args) {
ArrayList<String> in = new ArrayList<String>();
Scanner s = new Scanner(System.in);
while (s.hasNextLine() == true){
in.add(s.nextLine());
//infinite loop
}
}
I'm not even sure why the loop executes the first time. I believe the hasNextLine() should be false the first time ,since no input was taken yet. Any help or clarification appreciated.

You could use the empty line as a loop-breaker:
while (s.hasNextLine()){ //no need for "== true"
String read = s.nextLine();
if(read == null || read.isEmpty()){ //if the line is empty
break; //exit the loop
}
in.add(read);
[...]
}

You could end the loop with something like below. Here, the String "END" (case-insenstive) is used to signify end of the multi-line content:
public static void main(String[] args) {
ArrayList<String> in = new ArrayList<String>();
Scanner s = new Scanner(System.in);
while (s.hasNextLine()) {
String line = s.nextLine();
in.add(line);
if (line != null && line.equalsIgnoreCase("END")) {
System.out.println("Output list : " + in);
break;
}
}
}

You can use this code. It returns when the user press Enter on an empty line.
import java.util.Scanner;
import java.util.ArrayList;
public class Main {
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
ArrayList<String> arrayLines = new ArrayList<>();
String line;
while(true){
line = scanner.nextLine();
if(line.equals("")){
break;
}
else {
System.out.println(line);
arrayLines.add(line);
}
}
System.out.println(arrayLines);
}
}
Best

You can do somthing like this:
while (s.hasNextLine() == true){
String line = s.nextLine();
if ("".equals(line)) {
break;
}
in.add(line);
//infinite loop
}

Related

Java Array List - finding duplicate in While loop

I tried solving this ArrayList problem but no luck
Anyway in while loop I have to add new String items to the ArrayList.
If there is a duplicate item there should be a message that says REPEATED ITEM.
While loop will break by word END
public static void main(String[] args) {
ArrayList<String> lista1 = new ArrayList<>();
Scanner in = new Scanner(System.in);
while(true) {
System.out.println("enter words: ");
lista1.add(in.nextLine());
if(lista1.containsAll(lista1)){
System.out.println("Repeated words");
}
if(lista1.contains("end")) {
break;
}
}
for(String data:lista1)
System.out.println(data);
}
If I understand what you're trying to do correctly, I believe it appears that you're trying to loop over user input until they type "end", each input to a list, and state if you already added that word by printing out "repeated word". If that's the case, you're pretty close. You just need to understand how to use the list data structure a little bit better.
public static void main(String[] args) {
ArrayList<String> lista1 = new ArrayList<>();
Scanner in = new Scanner(System.in);
while(true) {
System.out.println("enter words: ");
String userInput = in.nextLine();
if (lista1.contains(userInput)) { // checks if user's input is already in lista1
System.out.println("Repeated word: " + userInput);
} else { // if it's not, then add user's input to lista1
lista1.add(userInput);
}
if (lista1.contains("end")) { // if lista1 contains "end", exit loop
break;
}
}
for(String data:lista1)
System.out.println(data);
}

Java BufferedReader readLine() suddenly not working after read()

I am currently having a problem with my loop. After I inputted a string once, it prompts the user and when the loop conditions were met, it just keeps asking the user "do you want to continue?" and was unable to enter another string.
public static void main(String[] args) throws IOException
{
BufferedReader bfr = new BufferedReader(new InputStreamReader(System.in));
LinkedList<String> strList = new LinkedList();
char choice;
do
{
System.out.print("Add Content: ");
strList.add(bfr.readLine());
System.out.print("Do you want to add again? Y/N?");
choice = (char)bfr.read();
}
while(choice == 'Y');
}
You need to get the newline character out of the keyboard buffer. You can do this like this:
do
{
System.out.print("Add Content: ");
strList.add(bfr.readLine());
System.out.print("Do you want to add again? Y/N?");
//choice = (char)bfr.read();
choice = bfr.readLine().charAt(0); // you might want to check that a character actually has been entered. If no Y or N has been entered, you will get an IndexOutOfBoundsException
}
while(choice == 'Y');
Usually the terminal only sends the data once you hit enter. So you get an empty line when you perform readLine again. You have to read a line, then check if it contains Y instead. Or read the empty line afterwards, whichever you think is less error prone.
I tend to use the earlier and read a full line, then check what it contains.
Don't forget that for something simple as this program you can use the convenient java.io.Console class.
Console console = System.console();
LinkedList<String> list = new LinkedList<>();
char choice = 'N';
do {
System.out.print("Add Content: ");
list.add(console.readLine());
System.out.print("Do you want to add again? Y/N?\n");
choice = console.readLine().charAt(0);
} while (choice == 'Y' || choice == 'y');
This work (don't forget library):
public static void main(String[] args) throws IOException
{
BufferedReader bfr = new BufferedReader(new InputStreamReader(System.in));
List<String> strList = new ArrayList<String>();
String choice;
do {
System.out.println("Add Content: ");
strList.add(bfr.readLine());
System.out.println("Do you want to add again? Y/N?");
choice = bfr.readLine();
} while(choice.equals("Y"));
System.out.println("End.");
}
Try this :
public static void main(String[] args) throws IOException
{
Scanner scan=new Scanner(System.in);
LinkedList<String> strList = new LinkedList();
String choice;`
do
{
System.out.print("Add Content: ");
strList.add(scan.nextLine());
System.out.print("Do you want to add again? Y/N?");
choice = scan.nextLine();
}
while(choice.equals("Y"));
}

how to read strings from user till encountering a new-line (Java)?

So the problem is that I want to read multiple lines of a string and put them into an ArrayList as long as the user doesn't go to the next line without entering anything.
Here is what the sample input looks like:
hello
I am John
here is the code I tried but it didn't work. (The error was: "String index out of range: 0".)
Scanner input = new Scanner(System.in);
ArrayList<String> text = new ArrayList<>();
while (true) {
String temp = input.nextLine();
if (temp.charAt(0) == '\n') {
break;
}
text.add(temp);
}
You can try if (temp.isEmpty()) as Scanner will read an empty String.
Scanner input = new Scanner(System.in);
List<String> text = new ArrayList<>();
while (true) {
String temp = input.nextLine();
if (temp.isEmpty()) break;
text.add(temp);
}
nextLine() removes the line terminator. See the Javadoc.
You should be testing the line for being empty.
You can use https://docs.oracle.com/javase/7/docs/api/java/io/BufferedReader.html
And the method readLine instead of Scanner.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class Test {
public static void main(String[] args) throws IOException {
List<String> text = new ArrayList<>();
System.out.println("Start input lines, press enter to stop: ");
try(BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) {
String line;
for(;;) {
line = reader.readLine();
if(null == line || line.length() == 0)
break;
text.add(line);
}
}
System.out.println("Echo: ");
text.stream().forEach((String str)-> {
System.out.println(str);
});
}
}

Java Scanner get a number of input from the users and print out

I am working on a small program. I need to get a number of integers from the user and print them out. I also need to identify whether the input is valid or not. Here is my code:
List<Integer> tokens = new ArrayList<Integer>();
Scanner sc = new Scanner(System.in);
while(sc.hasNextInt()) {
tokens.add(sc.nextInt());
System.out.println(sc.nextInt());
}
My first question is how to identify the type of the input and store this information in a variable.
My second question is I enter an infinite loop when I run the code. After I enter the input, the program prints all of them and then waits for input again. How do I solve this problem?
I really appreciate your help.
This might help you:
Why are You calling sc.nextInt() 2 times in the loop without checking for next value?
Use an invalid number such as -1 to break the loop.
Don't forget to close the stream.
sample code:
List<Integer> tokens = new ArrayList<Integer>();
try (Scanner sc = new Scanner(System.in)) {
while (sc.hasNextInt()) {
int i = sc.nextInt();
if (i == -1) {
break;
}
tokens.add(i);
System.out.println(i);
}
}
System.out.println(tokens);
Read Java7- The try-with-resources Statement
Try this code -
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Stax {
public static void main(String[] args) {
List<Integer> tokens = new ArrayList<Integer>();
Scanner sc = new Scanner(System.in);
String data = "";
System.out.println("Enter some numbers...");
while (sc.hasNext()) {
data = sc.next();
if (data.equalsIgnoreCase("EXIT")) {
System.out.println();
break;
}
try {
tokens.add(Integer.parseInt(data));
System.out.println(sc.next());
} catch (NumberFormatException e) {
System.out
.println("Error: Your input string cannot be converted to a number.");
e.printStackTrace();
}
}
}
}

What's wrong with this file Scanner code?

I am trying to search the File for characters in Java language. For that I am using Scanner to scan the file.
Well to check the Heirarchy work, I am using System.out.print("Worked till here!"); so that I can check whether it is executed or not. I was able to execute the code till the last stage, but then I found that the essential boolean variable wasn't altered, which was under the condition to check whether there is a character match or not.
The file contents are as
Ok, here is some text!
Actually this file is created to test the validity of the java application
Java is my favourite programming language.
And I think I can score even more :)
Wish me luck!
However, no matter what I search it always prompts me to be false.
Here is the code I am using
public static void main (String[] args) throws IOException {
// Only write the output here!!!
System.out.print("Write the character to be found in the File: ");
Scanner sc = new Scanner(System.in);
String character = sc.next();
// Find the character
System.out.println("Searching now...");
getCharacterLocation(character);
// Close the resource!
sc.close();
}
The method call executed and the method is as
public static void getCharacterLocation (String character) throws IOException {
System.out.println("File found...");
File file = new File("res/File.txt");
Scanner sc = new Scanner(file);
int lineNumber = 0;
int totalLines = 0;
boolean found = false;
// First get the total number of lines
while(sc.hasNextLine()) {
totalLines++;
sc.nextLine();
System.out.println("Line looping! For Total Lines variable.");
}
int[] lineNumbers = new int[totalLines];
int lineIndex = 0;
System.out.println("Searching in each line...");
while(sc.hasNextLine()) {
// Until the end
/* Get each of the character, I mean string from
* each of the line... */
while(sc.hasNext()) {
// Until the end of line
String characterInLine = sc.next();
if(sc.findInLine(character) != null) {
found = true;
}
}
System.out.print(sc.nextLine() + "\n");
lineNumber++;
sc.nextLine();
}
System.out.println("Searching complete, showing results...");
// All done! Now post that.
if(found) {
// Something found! :D
System.out.print("Something was found!");
} else {
// Nope didn't found a fuck!
System.out.println("Sorry, '" + character +
"' didn't match any character in file.");
}
sc.close();
}
Never mind the extra usage of variables, and arrays. I would use it in further coding if I can get the character and set the value to true.
Here is the output of this program.
Initial Stage
This is the initial stage for that. I wrote Ok in the input field, you can see Ok is the very first character in the File too.
Final Stage
This is the result after the execution.
Any help in this?
You count lines and don't restart the scanner.
boolean found = false;
// First get the total number of lines
while(sc.hasNextLine()) {
totalLines++;
sc.nextLine();
System.out.println("Line looping! For Total Lines variable.");
}
int[] lineNumbers = new int[totalLines];
int lineIndex = 0;
System.out.println("Searching in each line..."); // <------
while(sc.hasNextLine()) {
add e.g.
UPDATED from the comment
sc.close();
sc = new Scanner(file);
before the next while(sc.hasNextLine())
You need to implement a way to string your characters together and check them against your input. It appears that you don't currently have a way to do this in your code.
Try building an array of characters with your scanner, and moving through and doing a check of your input vs the indexes. Or maybe there is a way to implement the tonkenizer class achieve this.
Put remember, what you are looking for is not a character, it is a string, and you need to keep this in mind when writing your code.
When you count your lines you use while(sc.hasNextLine()).
After this loop, your scanner is behind the last line, so when you go to your next loop while(sc.hasNextLine()) { it is never executed.
There are multiple problems with your code:
You Iterated through your scanner here:
while(sc.hasNextLine()) {
totalLines++;
sc.nextLine();
System.out.println("Line looping! For Total Lines variable.");
}
So after this you have to reset it again to read for further processing.
While searching for character you are having two loops:
while(sc.hasNextLine()) {
// Until the end
/* Get each of the character, I mean string from
* each of the line... */
while(sc.hasNext()) {
// Until the end of line
String characterInLine = sc.next();
if(sc.findInLine(character) != null) {
found = true;
}
}
Here you just need a single loop like:
while(sc.hasNextLine()) {
String characterInLine = sc.nextLine();
if(characterInLine.indexOf(character) != -1) {
found = true;
break;
}
}

Categories

Resources