how to read ints from file?

  • (2 Pages)
  • +
  • 1
  • 2

19 Replies - 1358 Views - Last Post: 16 February 2015 - 10:32 AM Rate Topic: -----

#1 Spiked Penguin   User is offline

  • D.I.C Head

Reputation: -2
  • View blog
  • Posts: 107
  • Joined: 19-December 13

how to read ints from file?

Posted 14 February 2015 - 07:14 PM

I have my file to createNewFile and LoadGame when I create a new file it makes the file and when I save it keeps the last saved data but, when I load it I don't know how to change the players stats to what's inside the file.

LoadGame.java
package com.hunt.game;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class LoadGame {
	
	public void PlayerContents(){
		
		BufferedReader br = null;
		
		try {
			String sCurrentLine;
			br = new BufferedReader(new FileReader("C:/Users/AncientPandas/Desktop/HuntersConquest/player.txt"));
		while((sCurrentLine = br.readLine()) != null){
			System.out.println(sCurrentLine);
		}
		} catch(IOException e){ e.printStackTrace();}
		finally {
			try {
				if (br != null)br.close();
			} catch (IOException ex){
				ex.printStackTrace();
			}
		}
	}

}



Player.java
package com.hunt.game;

import java.util.Scanner;

public class Player {

	public static int atk = 5, def = 3, dmg, exp = 0, currentLife = 10, maxLife = 10, level = 1,
			exptoLevel = 25, statPoints = 0, amount;
	Main main = new Main();
	
	public void PlayerStats(){
		
	@SuppressWarnings("resource")
	Scanner scanner = new Scanner(System.in);
	int choice = 0;
	
	System.out.println("Level: " + level + "\nAtk: " + atk + "\nDef: " + def + "\nLife: " + currentLife + 
			" / " + maxLife + "\nExp: " + exp + " / " + exptoLevel + "\n\n");
	do{
	if(statPoints > 0){
		System.out.println("Level: " + level + "\nAtk: " + atk + "\nDef: " + def + "\nLife: " + currentLife + 
				" / " + maxLife + "\nExp: " + exp + " / " + exptoLevel + "\n\n");
		System.out.println("The Player has " + statPoints + " unused stat points. Would you like to spend them now?");
		System.out.println("(1) Yes\n(2) No");
		choice = scanner.nextInt();
		if(choice == 1){
			System.out.println("What would you like to spend your stat points on?");
			System.out.println("(1) Attack\n(2) Defense\n(3) Life\n(4) Do not spend");
			choice = scanner.nextInt();
			if(choice == 1){
				do{
				System.out.println("How many stat points would you like to spend on Attack? ");
				amount = scanner.nextInt();
				if(amount > statPoints){
					System.out.println("Sorry you can only use the amount of stat points you have.");
				}
				}while(amount > statPoints);
				atk = atk + amount;
				statPoints = statPoints - amount;
				main.run();
				}
			else if(choice == 2){
				while(amount > statPoints);{
					System.out.println("How many stat points would you like to spend on Defense? ");
					amount = scanner.nextInt();
					if(amount > statPoints){
						System.out.println("Sorry you can only use the amount of stat points you have.");
					}
					}while(amount > statPoints);
					def = def + amount;
					statPoints = statPoints - amount;
					main.run();
					}
			else if(choice == 3){
				do{
				System.out.println("How many stat points would you like to spend of Life? ");
				amount = scanner.nextInt();
				if(amount > statPoints){
					System.out.println("Sorry you can only use the amount of stat point you have.");
				}
				}while(amount > statPoints);
				maxLife = maxLife + amount;
				statPoints = statPoints - amount;
				currentLife = maxLife;
				main.run();
			}
			else if(choice == 4){System.out.println("You have chosen not to spend any of your stat points.");
			main.run();
			}
			}
		}
		else if(choice == 2){
			main.run();
		}
	
	}while(choice > 4 && choice < 1);
	main.run();
	}
}



Player.txt

Quote

Attack: 5
Defence: 4
Damage: 3
Current Life: 13
Current experience: 37
Experience to level: 45
Level: 2
Max Life: 13
Stat Points: 0


I am trying to load these stats ^

Is This A Good Question/Topic? 0
  • +

Replies To: how to read ints from file?

#2 macosxnerd101   User is offline

  • Games, Graphs, and Auctions
  • member icon




Reputation: 12800
  • View blog
  • Posts: 45,992
  • Joined: 27-December 08

Re: how to read ints from file?

Posted 14 February 2015 - 07:23 PM

I would do a lot of refactoring. Your code is poorly designed and hard to follow. The Player class should model the Player. Another class should manage the Player(s) of the game. Then there should be a class to handle File I/O. There shouldn't be any user interaction or file interaction in the Player class.

Your Player class should model the Player data and include getter/setter methods as appropriate. You use the setter methods on the Player object to modify the stats.
Was This Post Helpful? 0
  • +
  • -

#3 Spiked Penguin   User is offline

  • D.I.C Head

Reputation: -2
  • View blog
  • Posts: 107
  • Joined: 19-December 13

Re: how to read ints from file?

Posted 14 February 2015 - 07:29 PM

Ummm, I don't have anything that's not resembling the player in there? I just reference the objects of player in load and save.

EDIT: Didn't come to get criticized... Get me jon.kiparsky lol I like his responses he can be very useful.

This post has been edited by Spiked Penguin: 14 February 2015 - 07:30 PM

Was This Post Helpful? -1
  • +
  • -

#4 macosxnerd101   User is offline

  • Games, Graphs, and Auctions
  • member icon




Reputation: 12800
  • View blog
  • Posts: 45,992
  • Joined: 27-December 08

Re: how to read ints from file?

Posted 14 February 2015 - 07:42 PM

Quote

Ummm, I don't have anything that's not resembling the player in there?

Yes you do. You shouldn't be handling user interactions in the Player class.

Your fields shouldn't be static either. What happens when you have multiple Players? They can't have unique stats then.

Getting up to speed on the basics of OOP is probably worthwhile to do here. It will help you clean your code up and better organize it rather than trying to apply band-aid fixes which are making things worse.

I'm pretty sure Jon is going to tell you the same thing I am. And if you're doing something wrong (which you are), better to get it fixed up front than to have it cause issues down the road (which it will). ;)
Was This Post Helpful? 0
  • +
  • -

#5 Spiked Penguin   User is offline

  • D.I.C Head

Reputation: -2
  • View blog
  • Posts: 107
  • Joined: 19-December 13

Re: how to read ints from file?

Posted 14 February 2015 - 08:49 PM

It's a single player text based adventure game. You can only have 1 file... Like wtf? Please stop assuming things... It really bothers me when people assume things, when they don't know what the other person is doing.

EDIT: So instead of criticizing me as a person and my project setup based off my design for a SINLGLE player game will you please, help and answer my question?

This post has been edited by Spiked Penguin: 14 February 2015 - 08:50 PM

Was This Post Helpful? -1
  • +
  • -

#6 macosxnerd101   User is offline

  • Games, Graphs, and Auctions
  • member icon




Reputation: 12800
  • View blog
  • Posts: 45,992
  • Joined: 27-December 08

Re: how to read ints from file?

Posted 14 February 2015 - 09:11 PM

Woah- chillax there. Nobody is attacking you personally.

Use of static is still poor practice. I'm not sure why you are opposed to using good practices, but whatever. I did offer advice- make some minor tweaks to your Player class to include setter methods. Then create a Player object and use the setter methods appropriately.
Was This Post Helpful? 0
  • +
  • -

#7 Spiked Penguin   User is offline

  • D.I.C Head

Reputation: -2
  • View blog
  • Posts: 107
  • Joined: 19-December 13

Re: how to read ints from file?

Posted 14 February 2015 - 09:40 PM

Googling it, I'm not to sure I understand the concept of encapsulation but, that's why to you and I'm sure others consider this sloppy. However I try to learn by experience so, in simple terms lol could you try to explain getters/setters please? Because, I am not sure if what you are wanting me to do is put all the player traits into one or multiple methods idk, #confused.

Trying a different approach in my loadGame.java

package com.hunt.game;

import java.util.Scanner;

public class LoadGame {
	
	public Scanner x;
	
	public void openFile(){
		try{
			x = new Scanner("C:/Users/AncientPandas/Desktop/HuntersConquest/player.txt");
		} catch (Exception e){
			System.out.println("Could not load previous save file.");
		}
	}

	
	public void readFile(){
		while(x.hasNext()){
			String a = x.next();	
			
			System.out.printf("%s\n", a);
		}
	}
	
	public void closeFile(){
		x.close();
	}
}



but, is there a way I can change the scanner to read from that file location or should I add it to the workspace?

This post has been edited by Spiked Penguin: 14 February 2015 - 10:09 PM

Was This Post Helpful? 0
  • +
  • -

#8 macosxnerd101   User is offline

  • Games, Graphs, and Auctions
  • member icon




Reputation: 12800
  • View blog
  • Posts: 45,992
  • Joined: 27-December 08

Re: how to read ints from file?

Posted 14 February 2015 - 10:24 PM

Give my tutorial Moving Away From Parallel Arrays a read. It's really the best resource I have regarding class design.

Even though you have a single Player in the game, encapsulation and proper class design will help you better model the Player's interactions with other objects. It also goes towards extensibility, where you can better scale for multiple Players.

Here is a sketch of how I see things appearing:
public class Player{

   private int attack;
   //other instance variables

   public Player(){
       this.attack = 0; //initialize each instance variable
   }

   public int getAttack(){ return this.attack; }
 
   public void setAttack(int attack){
      //set the instance variable
      //to the value of the parameter
      this.attack = attack; 
   }
}



Does this help you get started?

Quote

but, is there a way I can change the scanner to read from that file location or should I add it to the workspace?


Replace filepath with the path of the File.
Scanner scan = new Scanner(new File("filepath"));


Was This Post Helpful? 3
  • +
  • -

#9 jon.kiparsky   User is offline

  • Beginner
  • member icon


Reputation: 12350
  • View blog
  • Posts: 20,984
  • Joined: 19-March 11

Re: how to read ints from file?

Posted 14 February 2015 - 10:40 PM

Okay, steady on there, friend. Mac's advice is sound - as usual. Good programming practice is always worth mentioning. In fact, I'll mention another piece of programming practice: a class name should be a noun. A class represents something, whether it's something in the world (Cat, Airplane , Anvil) or something abstract (Mammal, ContinuedFraction, Solipsism) or something that's just a programming construct (File, Scanner). So I worry when I see "LoadGame.java". Perhaps you might want to make a GameLoader. In fact, you might easily want to make a GameLoader interface, and implement it in different ways for different situations (an android version of your game will probably load stuff differently from the browser version which will be different again from the one that runs on the user's desktop machine.
I'm sure this sounds like pedantic chin-stroking and completely useless to your present situation, but it's really important that you think about these things now, while you're working on easy problems, so they become habits when you start working on harder problems. As a programmer, you're always going to want to be able to take on the hardest problems you can manage, and the best way to do that is to make programming itself as easy as possible. Good habits are a big part of that. They keep you from getting in your own way.

Another thing that I don't like to see is "suppressWarnings". The warnings are your friends. They're there to stop you from shooting yourself in the foot.

Okay, but enough of that. You're having trouble loading the data. One problem is that your representation of the situation doesn't really make your life easy. You have a sort-of mapping of keys to values in the file, but there is no good way to assign those values to the individual fields in the file without doing some explicit conditional logic on each item that you read - that's boring and hard to work with. Let's be smart and easy instead.

What I want you to do is to get happy with the idea of a HashMap. Instead of having a dozen individual stats stored as individual variables, i want you to make a HashMap storing the stats as named entities. When you've done that, it will be very, very easy to fill in the blanks in this method:

private Player loadPlayerFromFile(String fileName) {
  // make a HashMap, stats
  // open the file
  // for each line in the file 
  //    split the line into key, value
        add key, value to stats
  // make a Player using this stats map
}




Quote

Get me jon.kiparsky lol I like his responses he can be very useful.


Thanks for that - but if I'm off taking in a show with the girlfiend, there are plenty of sharp heads out there who know as much as I do or more, and you should be ready to take advice from them as well. And if you don't see the point of what they're saying, I would rather you take the trouble to engage and work with them. They're giving you good advice because they want to help you - they're not trying to yank your chain.
Was This Post Helpful? 3
  • +
  • -

#10 Spiked Penguin   User is offline

  • D.I.C Head

Reputation: -2
  • View blog
  • Posts: 107
  • Joined: 19-December 13

Re: how to read ints from file?

Posted 15 February 2015 - 11:01 AM

@macosxnerd101 thank you for your answer of

Quote

Replace filepath with the path of the File.
Scanner scan = new Scanner(new File("filepath"));



Thank you for the help, maybe I will look deeper into that other thread. Jon.kiparsky I also appreciate your answer :)/>/> Thank you both. I thought about doing something similar to the Gameloader with loading / saving in the one and just using different methods but, I decided against it, kinda should go back and fix that lol. However I did end up being able to load and change the values now :)/>/>.

package com.hunt.game;

import java.io.File;
import java.util.Scanner;

public class LoadGame {
	
	public Scanner x;
	
	public void openFile(){
		try{
			x = new Scanner(new File("C:/Users/AncientPandas/Desktop/HuntersConquest/player.txt"));
		} catch (Exception e){
			System.out.println("Could not load previous save file.");
		}
	}
	
	public void readFile(){
		while(x.hasNext()){
			int a = x.nextInt();
			int b = x.nextInt();
			int c = x.nextInt();
			int d = x.nextInt();
			int e = x.nextInt();
			int f = x.nextInt();
			int g = x.nextInt();
			int h = x.nextInt();
			int i = x.nextInt();
			
			System.out.printf("Player attack: %s\nPlayer Defence: %s\n"
					+ "Player Damage: %s\nPlayer Life: %s/%s\n"
					+ "Player Experience: %s/%s\nPlayer Level: %s\n"
					+ "Player Stat Points: %s\n", a, b, c, d, e, f, g, h, i);
			
			Player.atk = a;
			Player.def = b;
			Player.dmg = c;
			Player.currentLife = d;
			Player.maxLife = e;
			Player.exp = f;
			Player.exptoLevel = g;
			Player.level = h;
			Player.statPoints = i;
		}
	}
	
	public void closeFile(){
		x.close();
	}
}



Suppression warnings I don't normally do, this is actually the only one I am using which I should just get rid of and close the scanner. (If that's the warning I am thinking you are talking about. I didn't go back and look to see the one you were talking about.)

This post has been edited by Atli: 15 February 2015 - 01:08 PM
Reason for edit:: Fixed quote tags.

Was This Post Helpful? 0
  • +
  • -

#11 jon.kiparsky   User is offline

  • Beginner
  • member icon


Reputation: 12350
  • View blog
  • Posts: 20,984
  • Joined: 19-March 11

Re: how to read ints from file?

Posted 15 February 2015 - 11:36 AM

Yeah, that approach to readFile will work - but if I saw a bunch of variables called "a", "b", "c", etc in a piece of code I was reviewing, I'd send it back to have that fixed. Use the names - even on something as small as that, take the extra two seconds to make it right. And as long as I'm hounding you about names - why not spell out "attack" and "damage"? This is actually a really important thing: make your code easy to read. Why make your life harder? Why not take the trouble to establish good habits now?

(And of course that diagnostic printout will need to go, but I assume that's just there so you can see that it's working, right?)
Was This Post Helpful? 0
  • +
  • -

#12 Spiked Penguin   User is offline

  • D.I.C Head

Reputation: -2
  • View blog
  • Posts: 107
  • Joined: 19-December 13

Re: how to read ints from file?

Posted 15 February 2015 - 01:16 PM

haha the diagnostic prinout I just like to have it. I mean, I guess I could just get rid of it because you can view it in the character page. Yeah, the a,b,c is a tad confusing so I will need to change that. Thank you, for your help Jon.
Was This Post Helpful? 0
  • +
  • -

#13 jon.kiparsky   User is offline

  • Beginner
  • member icon


Reputation: 12350
  • View blog
  • Posts: 20,984
  • Joined: 19-March 11

Re: how to read ints from file?

Posted 15 February 2015 - 01:19 PM

More programming practice: methods that do things shouldn't have side effects. A method that loads a file shouldn't also produce output to the screen.
If you want to be able to see what's happening, use logging - this is a good idea, actually. (no, I'm not going to write a tutorial on logging in java - there are plenty already!)
Was This Post Helpful? 0
  • +
  • -

#14 Spiked Penguin   User is offline

  • D.I.C Head

Reputation: -2
  • View blog
  • Posts: 107
  • Joined: 19-December 13

Re: how to read ints from file?

Posted 15 February 2015 - 02:57 PM

Not really related to this question anymore but, is their a way to make my random have a lower chance to get a certain number e.g

Random rand = new Random();
int i = rand.nextInt(6)+1;
// Where i i want to have it have a example chance of 10% chance of 6, %20 chance of 2, 50% chance of 1
System.out.println(i);




On a side note... I also merged my loadgame.java and savegame.java into Gameloader.java and added full words. Not really sure if this is what you meant or not but, I gave it a shot. I mean it's more convenient when I need to access both.

package com.hunt.game;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Scanner;

public class GameLoader {
	
	public Scanner x;
	
	public void openFile(){
		try{
			x = new Scanner(new File("C:/Users/AncientPandas/Desktop/HuntersConquest/player.txt"));
		} catch (Exception e){
			System.out.println("Could not load previous save file.");
		}
	}
	
	public void readFile(){
		
		try{
			
		while(x.hasNext()){
			int attack = x.nextInt();
			int defense = x.nextInt();
			int life = x.nextInt();
			int maxLife = x.nextInt();
			int currentExperience = x.nextInt();
			int experienceToLevel = x.nextInt();
			int level = x.nextInt();
			boolean infection = x.nextBoolean();
			int statPoints= x.nextInt();
			
			Player.atk = attack;
			Player.def = defense;
			Player.currentLife = life;
			Player.maxLife = maxLife;
			Player.exp = currentExperience;
			Player.exptoLevel = experienceToLevel;
			Player.level = level;
			Player.infection = infection;
			Player.statPoints = statPoints;
		}
		} catch (Exception e) {
			System.out.println("Corrupted File... Overwriting previous save file");
			NewGame();
		}
	}
	
	public void closeFile(){
		x.close();
	}
	
public void NewGame(){
		
		GameLoader gl = new GameLoader();
		Main main = new Main();
		Scanner scanner = new Scanner(System.in);
		int choice;
		
		System.out.println("Are you sure you would like to overwrite your previous save data?\n"
				+ "(1) Yes\n(2) No");
		choice = scanner.nextInt();
		do{
			if(choice == 1){
				try{
					File player = new File ("C:/Users/AncientPandas/Desktop/HuntersConquest/player.txt");
					FileOutputStream fos = new FileOutputStream(player);
					OutputStreamWriter osw = new OutputStreamWriter(fos);
					Writer writer = new BufferedWriter(osw);
					// What to write to file
					writer.write(String.valueOf(Player.atk));
					writer.write("\n");
					writer.write(String.valueOf(Player.def));
					writer.write("\n");
					writer.write(String.valueOf(Player.currentLife));
					writer.write("\n");
					writer.write(String.valueOf(Player.maxLife));
					writer.write("\n");
					writer.write(String.valueOf(Player.exp));
					writer.write("\n");
					writer.write(String.valueOf(Player.exptoLevel));
					writer.write("\n");
					writer.write(String.valueOf(Player.level));
					writer.write("\n");
					writer.write(String.valueOf(Player.infection));
					writer.write("\n");
					writer.write(String.valueOf(Player.statPoints));
					System.out.println("Successfully overwrote file.");
					writer.close();
					main.run();
				} catch (IOException e){
					System.err.println("An error has occured while saving game...");
			}
		} else gl.openFile(); gl.readFile(); gl.closeFile();
	} while (choice != 1 && choice != 2);
}
}


Was This Post Helpful? 0
  • +
  • -

#15 jon.kiparsky   User is offline

  • Beginner
  • member icon


Reputation: 12350
  • View blog
  • Posts: 20,984
  • Joined: 19-March 11

Re: how to read ints from file?

Posted 15 February 2015 - 03:07 PM

Quote

i want to have it have a example chance of 10% chance of 6, %20 chance of 2, 50% chance of 1


These only sum to 80%, so this is not very well specified, but you could make an array and draw at random from it. If you arrange the list correctly, the probabilities will be weighted. For example, drawing randomly from { 6, 2, 2, 1,1,1,1,1, 7,8} gives you the probabilities you've asked for (adding 10% chance of 7 and 10% chance of 8, to make this reasonable)

This is clunky if you want to do more complex percentages, though. You could also draw a random number in the range (0..1) and check the range that it falls into - this is a little more work to write, but it might be more robust in the long run.

If you're going to do real statistical modeling, look for a good stats package.
Was This Post Helpful? 1
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2