-1

I am attempting to read a text file that contains different values, then store the values into their respective arrays so that I can later verify scanner inputs. An example of the text file is below:

u1142592
87500
1
u1530078
125000
1
u2405234
105000
2

The first value is meant to be a string (representing a user ID), second is an int (user salary), and third is a boolean (determines if a user is a manager or not). I want to store each of these values in a separate array by their respective variable type, but I am very new to Java and I don't have any clue on how I could do this. Additionally, there are only 10 of each input (10 user IDs, etc), so I'm not sure if that helps or not.

What would I have to code in order to achieve my desired result? Thanks and I appreciate any help!

Eric Ryor
  • 3
  • 3

1 Answers1

1

You should store in User object. User object can be:

public class User {
    String id;
    int salary;
    boolean isManager;
    
    public User(String id, int salary, boolean isManager) {
        this.id = id;
        this.salary = salary;
        this.isManager = isManager;
    }
}

Now you can read all lines and create objects. Then put all objects into an array.

ArrayList<User> users = new ArrayList<>();

String id;
int salary;
boolean isManager;

Scanner scanner = new Scanner(new File("myfile.txt"));
int line = 1;
while (scanner.hasNextLine()) {
    if (line % 3 == 1) {
        id = scanner.nextLine();
    } else if (line % 3 == 2) {
        salary = Integer.parseInt(scanner.nextLine());
    } else if (line % 3 == 0) {
        isManager = scanner.nextLine().equals("1") ? true : false;
        
        User user = new User(id, salary, isManager);
        users.add(user);
    }
    
    line++;
}
scanner.close();

Now you have User list and you can use it as you want. But you should add exception controls in the code.

İsmet
  • 95
  • 3
  • 12