1

I am making a program where I have to read String from a text file and I did it using a scanner with this code:

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
    File file = new File(jTextField1.getText());
    c = new crows_word_game();
    ArrayList<String> list = new ArrayList<>();
    try {
        Scanner fileIn = new Scanner(file);
        String line;
        while(fileIn.hasNextLine()) {
            line = fileIn.nextLine();
            list.add(line);
        }
        c.setWords((String[]) list.toArray(),c);
    } catch (FileNotFoundException ex) {
        Logger.getLogger(readfile.class.getName()).log(Level.SEVERE, null, ex);
    }
}

and I have to store my array in an object which have an array build in it but when ever I do that it gives me an error saying:

cant cast an object to a string

My method and Class are below

class crows_word_game {

    public static puzzle_diagram shape;      
    public static int number;
    public static String[] words;
    public static int x,y,max;
    public static boolean rock=false;


    public crows_word_game(){ }

    public crows_word_game(puzzle_diagram p,int wordsnum){
        shape = p;
        number = wordsnum;
        //words = new String[number];
        //words = file;
        x=0;
        y=0;
        max=0;
    }

    public void setWords(String[] word,crows_word_game c) {
        for(int i=0;i<c.number;i++)
        c.words[i] = word[i];
    }
}

can you tell me whats wrong and what can i do to fix it

Java Devil
  • 10,629
  • 7
  • 33
  • 48
  • You can refer the answers from this similar question: https://stackoverflow.com/questions/3880274/how-to-convert-the-object-to-string-in-java. – Quang Vien May 23 '18 at 01:40
  • As a side note, class names should always begin with a capital letter. Take a look at the Java naming conventions [here](http://www.oracle.com/technetwork/java/codeconventions-135099.html). – Logan May 23 '18 at 02:34
  • 1
    Another side note: `List.toArray()` returns an `Object[]`. If you get the `Class` from an `Object[]` and a `String[]`, you'll find that they belong to totally different runtime classes. That is why you are having a cast exception. – Jai May 23 '18 at 03:03

0 Answers0