0
votes

Edit: added the braces {} and an Eclipse screenshot

I have a problem with a simple assignment to create a class that has an array list to store words from the command-line, with each word appended to the end of the array list, then search the list for a specific word ("the") and prints location of the word's occurences, plus another method to return a new array list with the words at the positions specified by a number.

I wrote the code below. In Eclipse IDE, it doesn't show any errors, but when I tried to run the code by Run Configurations and enter this dummy text: "The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog.", it doesn't work. I'm not sure why, could you give me advice? Thank you!

import java.util.ArrayList;
import java.util.Scanner;
class Search {
    ArrayList<String> list;

    public Search(){
        list = new ArrayList<String>();
    }

    public void read(){
        Scanner scanner = new Scanner(System.in);
        while(scanner.hasNext()) {
            list.add(scanner.next());
        }
        scanner.close();
    }

    public void find(String word){
        for(int i = 0; i < list.size(); i++) {
            if(list.get(i).equalsIgnoreCase(word)) {
                System.out.println(i);
            }
        }
    }

    public ArrayList<String> subsequence(int[] positions){
        ArrayList<String> result = new ArrayList<String>();
        for(int i = 0; i < positions.length; i++) {
            if(positions[i] >= 0 && positions[i] < list.size()) {
                result.add(list.get(positions[i]));
            }   
        }
        return result;
    }

    // Testing method within class again
    public static void main(String[] args){
        Search search = new Search();
        search.read();
        search.find("the");
        for(String s : search.subsequence(new int[]{0, 3, 4}))
            System.out.println(s);

    }
}  

Eclipse screenshot

1
Hi and welcome and thanks for sharing your tidy looking and well laid out code. Do please let us know exactly what happens when you try to run it, though I think you may me missing braces {} round a multi line block. Generally it is good practise to use braces round blocks even if only one line to avoid odd future bugs if somebody adds a lineChris
Also, I'm not too familiar with Scanner but does hasNext return a line of input (separated by carriage return). If so you will need to break that up into separate words.Chris
I don't think there are any missing braces, but the advice to use them still holds, it's especially confusing where you have if blocks inside loops. I know there is indentation, but when it comes to production code remember that not everybody that picks up your code formats it the same way, play it safe, get used to using braces. So do you input the sentence one word at a time, or whole sentence before hitting enter? If the latter then that may be your problem. If in doubt add a bit of System.out.println, or just debug through code to see what is happeningChris
Thank you Chris, noted on your advice - I've added the {} and @DeepDalsania has explained it below too :)javanoob
You pass them as arguments, yeah, but you don't use the args in the main method. Instead you try to read it from standard input. tl;dr: search.list.addAll(Arrays.asList(args)); instead of search.read();Johannes Kuhn

1 Answers

1
votes
  • As dear @Chris commented kindly use the braces while coding. I run your code in two different ways and I got the output.

  • First Way

  • If you want to use scanner.hashNext() with while then you should change your main() and read() like this

    public static void main(String[] args) {
        Search search = new Search();
        Scanner sc = new Scanner(System.in);
        String line = sc.nextLine();
        sc.close();
        search.read(line);
        search.find("the");
        for (String s : search.subsequence(new int[] { 0, 3, 4 })) {
            System.out.println(s);
        }
    }
    
    public void read(String line) {
            Scanner scanner = new Scanner(line).useDelimiter("\\s");
            while (scanner.hasNext()) {
                list.add(scanner.next());
            }
            scanner.close();
    }
    
    
  • A simple text scanner which can parse primitive types and strings using regular expressions.
  • A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. The resulting tokens may then be converted into values of different types using the various next methods.

  • The next() and hasNext() methods and their primitive-type companion methods first skip any input that matches the delimiter pattern, and then attempt to return the next token. Both hasNext() and next() may block waiting for further input. Whether a hasNext() block has no connection to whether or not its associated next method will block.

  • Second Way

  • If you want to use StringTokenizer then you should have to change just read() to your existing code.

    public void read(String line) {
        Scanner scanner = new Scanner(System.in);
        StringTokenizer st = new StringTokenizer(scanner.nextLine(), " ");
        while (st.hasMoreElements()) {
            list.add(st.nextElement().toString());
        }
        scanner.close();
    }
    
  • It is always better to use StringTokenizer for the string. The StringTokenizer class allows an application to break a string into tokens.

  • A StringTokenizer object internally maintains a current position within the string to be tokenized. Some operations advance this current position past the characters processed. A token is returned by taking a substring of the string that was used to create the StringTokenizer object.

Reference : Scanner and StringTokenizer