Reputation: 37
Here is what I would like to do. I want to create a simple text file with one string and one integer and have my program read from it in this format:
name 3
name2 4
name5 5
Just a string separated by a space and then an integer.
This is for a ranking system, so basically it takes the username of the member and sets their rank to the int, such as:
if (username.toLowerCase() == (stringFromFile)) {
rank = (rankFromFile)
}
I just cannot find anything on how to read multiple strings and ints from a file but test each one separately.
Here is the way I am doing it right now but I don't like how it looks in the code, so I would like to store the usernames elsewhere.
private void RankLoad() {
switch(username.toLowerCase()){
case "example":
rank = 3;
break;
case "example1":
rank = 0;
break;
case "example2":
rank = 0;
break;
case "example3":
rank = 0;
break;
}
Upvotes: 0
Views: 132
Reputation: 37
OP here, this is how I ended up doing it and I tested it and it works, if anyone has any suggestions I appreciate constructive criticism. Thanks
public void readStaff() throws FileNotFoundException{
Scanner input = new Scanner(new File("stafflist.txt"));
String player;
int rank;
while (input.hasNextLine()) {
player = input.next();
rank = input.nextInt();
if (player.equals(username.toLowerCase())){
rights = rank;
} else {
rights = 0;}}}
private void StaffLoad() {
try { readStaff(); } catch (FileNotFoundException e) {
System.out.println("Cannot Find stafflist.txt"); }}
Upvotes: 0
Reputation: 8300
use something like this Scanner scanner = new Scanner (new File("your_file.txt"));
scanner.useDelimiter(" ");
and then while(scanner.hasNext()) {scanner.next() // use it to retrieve next value}
Upvotes: 0
Reputation: 13222
Use a Scanner
and read the file line by line. Then split the line by spaces: line.split(" ");
Then parse the int
which will be [1]
of the array. Now you have your data parsed out so you can use it however you want...
Upvotes: 1