0

I'm trying to add whatever value that scanner read from the file into an ArrayList<Integer>, but for some reason it doesn't work; it keeps complaining that "java: incompatible types: java.lang.String cannot be converted to java.lang.Integer."

Can anyone help me what is wrong with this? It works with the String type of Arraylist but not with Integer types of arraylist. So, I am guessing this is the problem, but not exactly know what is going on.

/**
 * readFromFile method will read from the database file and save all usernames, 
 * passwords, and keys in the corresponding ArrayLists.If the file cannot open,
* output error message: <dbName> cannot open!
 * @param dbName The file name to save all users, passwords, and keys
 * @param users
 * @param pwds
 * @param keys
 */
public static void readFromFile(String dbName, ArrayList<String> users, ArrayList<String> pwds, ArrayList<Integer> keys) {
    Path path = Paths.get("dbName");
    Scanner scan = null;
    try {
        scan = new Scanner(path);
    } catch (IOException e) {
        System.out.println(dbName +"cannot"+ " open!");
    }

    for (int i=0; i<users.size(); i++) {
        users.add(scan.next());
        pwds.add(scan.next());
        keys.add(scan.next()); // This is where the problem occurs
    }
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
DikDikee
  • 1
  • 3

3 Answers3

1
  • The variable keys is defined as ArrayList<Integer>.
  • The output of scan.next() is a String.

The compiler recognizes this and so it will not allow you to insert a String into a List<Integer>. You need to parse the Integer out of the String prior to insertion or invoke the int-specific method on the Scanner.

keys.add(Integer.valueOf(scan.next()));
... or ....
keys.add(scan.nextInt());
vsfDawg
  • 1,425
  • 1
  • 9
  • 12
0

You need to use nextInt or to parse string value.

keys.add(scan.nextInt());
Akif Hadziabdic
  • 2,692
  • 1
  • 14
  • 25
0

correct to keys.add(Integer.parseInt(scan.nextLine())

public static void readFromFile(String dbName, ArrayList<String> users, ArrayList<String> pwds, ArrayList<Integer> keys) {
    Path path = Paths.get("dbName");
    Scanner scan = null;
    try {
        scan = new Scanner(path);
    } catch (IOException e) {
        System.out.println(dbName +"cannot"+ " open!");
    }

    for (int i=0; i<users.size(); i++) {
        users.add(scan.next());
        pwds.add(scan.next());
       keys.add(Integer.parseInt(scan.nextLine()) // This is where the problem occurs
    }