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);
});
}
}
Related
My apologies for the title wording, it was hard to explain in words.
What I am trying to do I this:
I have a .txt file that has
cheese cracker salt
bread butter ham
I want the user to be able to enter 'cheese' then type in pepper which will in turn update the file to become
cheese cracker pepper
bread butter ham
I am unsure how to go about editing the third word after I have the user input the first word.
Your algorithm could look like this:
read in the file
split it up by spaces (you will get an array)
put the result into a modifiable list (you can't easily insert into an array)
search for the index of a word
insert another entry by index (you can calculate the correct index from the result of step 4)
overwrite the file with the contents of the list, separated by additional spaces.
Here is a solution utilizing File module along with BufferedReader/BufferedWriter
packages
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
import java.util.Scanner;
import java.nio.file.*;
Driver program
public class Main{
public static void main(String[] args) throws IOException{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the file name: ");
String path = sc.nextLine();
Path p = Paths.get(path);
List <String> lines = Files.readAllLines(p);
System.out.println("Enter new word:");
String newWord = sc.nextLine();
System.out.println("Which word would you like " + newWord + " to replace?");
String oldWord = sc.nextLine();
for(int i = 0; i < lines.size(); i++){
String line = lines.get(i);
line = line.replace(oldWord, word); // if current word is old word, replace with new one
lines.set(i, line); // update list
}
readFile(path); // read here will output original list
writeListToFile(lines, path); // overwrite sample.txt file
readFile(path); // read here will output updated text file from path
sc.close();
}
helper functions
public static void readFile(String fileName){
try{
FileReader fr = new FileReader(fileName);
BufferedReader br = new BufferedReader(fr);
String line = br.readLine();
while(line != null){
System.out.println(line);
line = br.readLine();
}
br.close();
}catch(IOException e){
System.out.println("Error reading file");
}
}
public static void writeListToFile(List<String> list, String path){
try{
FileWriter fw = new FileWriter(path);
BufferedWriter bw = new BufferedWriter(fw);
for(int i = 0; i < list.size(); i++){
bw.write(list.get(i));
bw.newLine();
}
bw.close();
}catch(IOException e){
System.out.println("Error writing to file");
}
}
}
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
}
So I'm trying to write a Java program that allows a user to input words at the command line. The program should stop accepting words when the user enters "STOP". Store the words in an ArrayList. The word STOP should not be stored in the list.
Next, print the size of the list, followed by the contents of the list.
Then, remove the first and last words stored in the list, but only if the list has a length greater than two. Finally, reprint the contents of the list.
import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;
public class t2_lesson1_template {
public static void main (String str[]) throws IOException
{
ArrayList<String> list = new ArrayList<String>();
Scanner scan = new Scanner(System.in);
do
{
System.out.println("What would you like to add to the list?");
String input = scan.nextLine();
list.add(input);
}
while( scan.nextLine() != "STOP");
if ( list.size() < 2)
{
System.out.println(list);
System.out.println(list.size());
}
else
{
list.remove(0);
list.remove(list.size()-1);
System.out.println(list);
System.out.println(list.size());
}
}
}
It keeps on prompting the question, but never recognizes when "STOP" is the input. If somebody could please help me figure out what's wrong, it'd help a lot. Thank you!
In line:
scan.nextLine() != "STOP"
you compare references to two objects. If you need to compare objects you should use equals() method of Object.
Read about equals() in the documentation.
But there is another problem in your code. You read next line twice.
In loop and in while(...) statement.
Try this:
System.out.println("What would you like to add to the list?");
String input = scan.nextLine();
while(!input.equals("STOP"))
{
list.add(input);
input = scan.nextLine();
}
Change scan.nextLine() != "STOP" to while(!scan.nextLine().equalsIgnoreCase("stop")); and try.
Reason :
The String Literal "STOP" will not be be same as the String value "STOP" entered from the keyboard (in your case). == compares references. You have to check value of 2 Strings not references.
Try the below code:-
import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;
public class t2_lesson1_template {
public static void main(String str[]) throws IOException {
ArrayList<String> list = new ArrayList<String>();
Scanner scan = new Scanner(System.in);
System.out.println("What would you like to add to the list?");
String input = scan.nextLine();
while (!input.equals("STOP")) { // compare string using equals(Object o) method
list.add(input);
System.out.println("What would you like to add to the list?");
input = scan.nextLine();
}
System.out.println("Size of list = " + list.size());
System.out.println("Input list:-\n" + list);
if (list.size() > 2) {
list.remove(0);
list.remove(list.size() - 1);
System.out.println("List after removing first and last eliment:-\n" + list);
}
}
}
import java.io.*;
import static java.lang.System.*;
import java.util.Scanner;
import java.lang.Math;
import java.util.ArrayList;
public class U7_L1_Activity_One{
public static void main (String str[]) throws IOException {
ArrayList<String> list = new ArrayList<String>();
Scanner scan = new Scanner(System.in);
System.out.println("Please enter words, enter STOP to stop the loop.");
String input = scan.nextLine();
while (!input.equals("STOP")) { // compare string using equals(Object o) method
list.add(input);
input = scan.nextLine();
}
System.out.println(list.size());
System.out.println(list);
// System.out.println("Size of list = " + list.size());
//System.out.println("Input list:-\n" + list);
if (list.size() > 2) {
list.remove(0);
list.remove(list.size() - 1);
System.out.println(list);
// System.out.println("List after removing first and last eliment:-\n" + list);
}
System.out.println(list);
}
}
How can I store a sentence from a file to a string, and then store the next line, which is made up of numbers, to a string?
When I use hasNextline or nextLine, none of it works. I am so confused.
Scanner kb = new Scanner(System.in);
String secretMessage = null;
String message, number = null;
File file = new File(System.in);
Scanner inputFile = new Scanner(file);
while(inputFile.hasNext())
{
message = inputFile.nextLine();
number = inputFile.nextLine();
}
System.out.println(number + "and " + message);
You're looping over the entire file, overwriting your message and number variables, and then just printing them once at the end. Move your print statement inside the loop like this so it will print every line.
while(inputFile.hasNext())
{
message = inputFile.nextLine();
number = inputFile.nextLine();
System.out.println(number + "and " + message);
}
One suggestion I would have for reading lines from a file would be to use the Files.readAllLines() method.
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
public class Display_Summary_Text {
public static void main(String[] args)
{
String fileName = "//file_path/TestFile.txt";
try
{
List<String> lines = Files.readAllLines(Paths.get(fileName), Charset.defaultCharset());
String eol = System.getProperty("line.separator");
for (int i = 0; i <lines.size(); i+=2)
{
System.out.println(lines.get(i).toString() + "and" + lines.get(i+1) + eol);
}
}catch(IOException io)
{
io.printStackTrace();
}
}
}
Using this set up, you can also create a stringBuilder and Writer to save the output to a file very simply if needed.
I'm trying to load some data to a GUI from a text file using a scanner. I have two sections in my text file: Clubs and Members. The code runs okay for the Clubs section. For example, if I have 4 clubs in my list, all of them will be displayed, but for the Members section doesn't matter how many members are in the list, only the first member will be displayed. Here is my code:
public void load (String fileName) throws FileNotFoundException {
FileInputStream fileIn = new FileInputStream("Clubs.txt");
Scanner scan = new Scanner(fileIn);
while (scan.hasNextLine()){
String line = scan.nextLine();
if(line.equals("Members")){
String firstName = scan.next();
String lastName = scan.next();
Pupil p1 = new Pupil( firstName, lastName);
pupils[nbrPupils] = p1;
nbrPupils ++;
}
else if(line.equals("Clubs")){
while (scan.hasNext()){
String club = scan.nextLine();
Club aNewClub = new Club(club);
clubs[nbrClubs] = aNewClub;
nbrClubs ++;
}
}
Hint: you're doing while (scan.hasNext()) in the Clubs section, but you don't do so in the Members section.
convert from while loop to if condition because you just want to check if there is a next line
else if (line.equals("Clubs")) {
if (scan.hasNext()) {/////here if you use while loop , it will loop until the file is finish
String club = scan.nextLine();
}
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ReadFile {
/**
* #param args
* #throws Exception
*/
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
new ReadFile().load("");
}
public void load (String fileName) throws FileNotFoundException {
FileInputStream fileIn = new FileInputStream("C:\\Clubs.txt");
Scanner scan = new Scanner(fileIn);
boolean membersfound =false;
while (scan.hasNextLine()){
String line = scan.nextLine();
if(line.equals("Members") || membersfound){
String firstName = scan.next();
String lastName = scan.next();
System.out.println("Member "+firstName +":"+ lastName);
}
else if(line.equals("Clubs") ){
while (scan.hasNext()){
String club = scan.nextLine();
if( club.equals("Members")){
membersfound = true;
break;
}
System.out.println("Clubname :" + club
);
}
}
}
}
}
I could have modified the whole program . But i wanted to show you your mistake
Sample clubs.txt file
Members
member1
member2
member3
Clubs
club1
club2
club3
When you do scan.nextLine() it moves the scanner to the line after the one you currently read in. So if you continue to do scan.next() the scanner will start from the end of your current line (in this case line) and reads what's after it.
See here it says:
"Advances this scanner past the current line and returns the input that was skipped"
What you can to is just call split() or substring() on line and extract the information you need.