i_want_to_code
i_want_to_code

Reputation: 87

How to detect newline in an input

I am given this exercise, but I am having trouble finding a way to catch the new line. Can you please help me?

Write a program that reads user input until an empty line. For each non-empty string, the program splits the string by spaces and then prints the pieces that contain av, each on a new line. Here is mycode:

public class AVClub {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        ArrayList<String> str = new ArrayList();
        String line;
        while (!(line = scanner.nextLine()).equals("")){
            str.add(line);     
        }
        for(int i=0; i<str.size();i++){
            if(str.get(i).contains("av")){
                System.out.println(str.get(i));
            }
        }

    }
}

Upvotes: 0

Views: 1320

Answers (1)

Arvind Kumar Avinash
Arvind Kumar Avinash

Reputation: 79580

The following requirement has been wrongly implemented in your code:

For each non-empty string, the program splits the string by spaces and then prints the pieces that contain av, each on a new line.

It should be:

import java.util.ArrayList;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        ArrayList<String> str = new ArrayList();
        String line;
        System.out.print("Enter sentences (blank line to terminate): ");
        while (!(line = scanner.nextLine()).equals("")) {
            str.add(line);
        }
        System.out.println("Words containig 'av' are: ");
        for (int i = 0; i < str.size(); i++) {
            line = str.get(i);
            String[] words = line.split("\\s+"); // Split the string on spaces
            for (String word : words) {
                if (word.contains("av")) {
                    System.out.println(word);
                }
            }
        }
    }
}

Explanation: you have to check each word in every sentence whether the word contains av. Your code checks for av in each sentence.

A sample run:

Enter sentences (blank line to terminate): harry is a good boy
my name is avinash
Is there any seats available in the aviation training
hello world

Words containig 'av' are: 
avinash
available
aviation

Note: If you need to check av in a case insensitive way, do it as if (word.toUpperCase().contains("AV")).

Upvotes: 1

Related Questions