ISSUE:
When I run this everything works fine. Let's say that my chosen IDs are: 0001, 0002, 0003, 0004. And their infos: info1, info2, info3, info4. If I pass 0002 in the scanner I get info2. As you'd expect but if I pass in 0001 I'd expect to get info1 but instead I get nothing. I tried this with an array of fixed size 3 and it worked just fine. I changed to an ArrayList because I don't know how long the file would be. Why does this happen?
I'm a newbie in programming so please forgive my lack of knowledge about where to look for these things.
What my program does is, read in a file and add all the rows to an ArrayList and then asks for input from the user, the input should be in the format of xxxx or 4 characters.
The text file I made as an example looks as follows, no extra spaces on the lines:
0001
info1
4
0002
info2
5
0003
info3
9
0004
info4
10
0005
info5
3
The main class:
public class Main {
public static ArrayList<Gameobject> games = new ArrayList<>();
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(new File("objects.txt"));
String id, info;
int amount;
while(sc.hasNextLine()) {
id = sc.nextLine();
info = sc.nextLine();
amount = Integer.parseInt(sc.nextLine());
Gameobject s = new Gameobject(id, info, amount);
games.add(s);
System.out.println(s.getId());
}
sc = new Scanner(System.in);
info(sc.next());
}
The info method is as follows.
public static void info(String id){
for(Gameobject s : games){
if(s.getId().equals(id)){
System.out.println(s.getInfo());
}
}
}
And the class Gameobject
public class Gameobject {
String id, info;
int amount;
Gameobject(String id, String info, int amount) {
this.id = id;
this.info = info;
this.amount = amount;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getInfo() {
return info;
}
public void setInfo(String info) {
this.info = info;
}
public int getAmount() {
return amount;
}
public void setAmount(int amount) {
this.amount = amount;
}
}
I did some tests and passed in games.get(0).getId()
to the info method and it worked. That got me the ID "0001" from the Gameobject. However just passing in "0001" did not.