0

I wrote this program to read the input from the scanner and store it as an object using ArrayList. However, it didn't print the correct content when I tested it. Like I input: Apple Pie, the output is Words@4aa298b7, Words@7d4991ad.

Am I missing sth? here is my code:

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

public class W7E2 {
    public static void main(String[]args) {
        System.out.println("Please anter words: ");
        Scanner sc = new Scanner(System.in);
        String []w = sc.nextLine().split(" ");

        ArrayList<Words> word = new ArrayList<Words>();
        for(int i = 0; i < w.length; i++) {
            word.add(new Words(w[i]));
        }
        System.out.println(word);
    }
}

class Words {
    private String wor;

    public Words(String wor) {
        this.wor = wor;
    }       
}
deHaar
  • 17,687
  • 10
  • 38
  • 51
Eiko Leung
  • 13
  • 2
  • 6
  • Override the `toString()` in the class `Word` and output it like this in `W7E2`: `System.out.println(word.toString());`... Do you know how to override a method? – deHaar Sep 18 '18 at 06:49
  • Thank you for answering. But I don't know what override is. I am a beginner to java. Why override method is needed in this case? – Eiko Leung Sep 18 '18 at 06:57
  • In Java, every class inherits from the class `Object` and `Object` already has some methods, `toString()` amongst others. You can override inherited methods and provide your own implementation. Have a look at [this question and its answers](https://stackoverflow.com/questions/10734106/how-to-override-tostring-properly-in-java). You would basically write a method `public String toString()` in your class `Words` and return a `String` representation according to your wishes. – deHaar Sep 18 '18 at 07:11

0 Answers0