简体   繁体   中英

How to use variables from 'main' method in another class? Serialization

newbie here! I was working with Save/Load in Java and I got stomped. My code is properly saving and loading everything, but I can't get these loaded variables to use anywhere outside 'public static void main' in my loading class. What I mean is:

I have this saving class, which works perfectly ok:

package com.mestru.esport;

import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.util.Random;

public class NewPlayer {

public static void main (String args[])
{
    Random rand = new Random();

    int naturalTalent = rand.nextInt(10);
    int luck = rand.nextInt(20);
    int figure = rand.nextInt(50);
    int agility = rand.nextInt(30);
    int intelligence = rand.nextInt(30);
    int multiTasking = rand.nextInt(30);
    int stamina = rand.nextInt(30);

    try
    {
        FileOutputStream saveFile = new FileOutputStream("Player.sav");
        ObjectOutputStream save = new ObjectOutputStream(saveFile);

        save.writeObject(naturalTalent);
        save.writeObject(luck);
        save.writeObject(figure);
        save.writeObject(agility);
        save.writeObject(intelligence);
        save.writeObject(multiTasking);
        save.writeObject(stamina);

        save.close();
    }
    catch(Exception exc)
    {
        exc.printStackTrace();
    }
}
}

Then I have class which is designed to load and make loaded variables usable in other classes. If loading part works flawless, then I just can't use them outside of 'main' method.

package com.mestru.esport;
import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.util.Random;

public class Player
{
int naturalTalent;
int luck;
int figure;
int agility;
int intelligence;
int multiTasking;
int stamina;

public static void main (String args[]) {

    int NEWnaturalTalent = 0;
    int NEWluck = 0;
    int NEWfigure = 0;
    int NEWagility = 0;
    int NEWintelligence = 0;
    int NEWmultiTasking = 0;
    int NEWstamina = 0;


    try {
        FileInputStream saveFile = new FileInputStream("Player.sav");
        ObjectInputStream save = new ObjectInputStream(saveFile);

        NEWnaturalTalent = (Integer) save.readObject();
        NEWluck = (Integer) save.readObject();
        NEWfigure = (Integer) save.readObject();
        NEWagility = (Integer) save.readObject();
        NEWintelligence = (Integer) save.readObject();
        NEWmultiTasking = (Integer) save.readObject();
        NEWstamina = (Integer) save.readObject();

        save.close();
    } catch (Exception exc) {
        exc.printStackTrace();
    }
    Player player = new Player();

    player.naturalTalent = NEWnaturalTalent;
    player.luck = NEWluck;
    player.figure = NEWfigure;
    player.agility = NEWagility;
    player.intelligence = NEWintelligence;
    player.multiTasking = NEWmultiTasking;
    player.stamina = NEWstamina;

}

public void test ()
{
    System.out.println("Natural Talent: " + naturalTalent);
    System.out.println("Luck: " + luck);
    System.out.println("Figure: " + figure);
    System.out.println("Agility: " + agility);
    System.out.println("Intelligence: " + intelligence);
    System.out.println("Multitasking: " + multiTasking);
    System.out.println("Stamina: " + stamina);
}

}

When I'm using method 'test' in another class, all values equal 0.

So here's my question. Can I somehow make all my instance variables equal those loaded inside 'main' method? I can't use "try" outside 'main' method as well :(

Thanks in advance for help <3 Every clue is appreciated, I've just started learning.

When you are loading, you create a new Player, set it and then discard it.

Perhaps you intended to set the fields of the current Player.

Also you don't need the temporary variables. You can just set the fields.

public static void main(String... ignored) throws IOException {
    Player player = new Player();
    player.load("Player.sav");
    player.test();
}

public void load(String filename) throws IOException {
  try (FileInputStream saveFile = new FileInputStream(filename);
    ObjectInputStream save = new ObjectInputStream(saveFile)) {
    naturalTalent = (Integer) save.readObject();
    luck = (Integer) save.readObject();
    figure = (Integer) save.readObject();
    agility = (Integer) save.readObject();
    intelligence = (Integer) save.readObject();
    multiTasking = (Integer) save.readObject();
    stamina = (Integer) save.readObject();
  }
}

Instead of writing this data in a binary form, you could write it as text. This would make it easier to read/edit and it would be more compact in this use case. ie Serializing an Integer object can be surprising large.

JavaCode For Main Class

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Random;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class TestProgram {

    public static void main(String[] args) throws FileNotFoundException {
        // TODO Auto-generated method stub

        Random rand = new Random();
        ArrayList<Integer> arl = new ArrayList<Integer>();

        int naturalTalent = rand.nextInt(10);
        int luck = rand.nextInt(20);
        int figure = rand.nextInt(50);
        int agility = rand.nextInt(30);
        int intelligence = rand.nextInt(30);
        int multiTasking = rand.nextInt(30);
        int stamina = rand.nextInt(30);

        String fileName = "/Users/rk4262/Player.txt";
        try {
            // Assume default encoding.
            FileWriter fileWriter = new FileWriter(fileName);

            // Always wrap FileWriter in BufferedWriter.
            BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);

            // Note that write() does not automatically
            // append a newline character.
            bufferedWriter.write("naturalTalent value is :" + naturalTalent);
            bufferedWriter.newLine();
            bufferedWriter.write("luck value is : " + luck);
            bufferedWriter.newLine();
            bufferedWriter.write("figure value is : " + figure);
            bufferedWriter.newLine();
            bufferedWriter.write("agility value is : " + agility);
            bufferedWriter.newLine();
            bufferedWriter.write("intelligence value is : " + intelligence);
            bufferedWriter.newLine();

            // Always close files.
            bufferedWriter.close();
        } catch (IOException ex) {
            System.out.println("Error writing to file '" + fileName + "'");
            // Or we could just do this:
            // ex.printStackTrace();
        }

        Player p = new Player();
        String s = p.readLine();
        System.out.println(s);

        Pattern pattern = Pattern.compile("[0-9]+");
        Matcher m = pattern.matcher(s);
        while (m.find()) {
            int n = Integer.parseInt(m.group());
            arl.add(n);

        }

        p.NEWnaturalTalent = arl.indexOf(0);
        p.NEWluck=arl.indexOf(1);
        p.NEWfigure=arl.indexOf(2);
        p.NEWagility=arl.indexOf(3);

    }

}

Code for Player Class

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Random;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class TestProgram {

    public static void main(String[] args) throws FileNotFoundException {
        // TODO Auto-generated method stub

        Random rand = new Random();
        ArrayList<Integer> arl = new ArrayList<Integer>();

        int naturalTalent = rand.nextInt(10);
        int luck = rand.nextInt(20);
        int figure = rand.nextInt(50);
        int agility = rand.nextInt(30);
        int intelligence = rand.nextInt(30);
        int multiTasking = rand.nextInt(30);
        int stamina = rand.nextInt(30);

        String fileName = "/Users/rk4262/Player.txt";
        try {
            // Assume default encoding.
            FileWriter fileWriter = new FileWriter(fileName);

            // Always wrap FileWriter in BufferedWriter.
            BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);

            // Note that write() does not automatically
            // append a newline character.
            bufferedWriter.write("naturalTalent value is :" + naturalTalent);
            bufferedWriter.newLine();
            bufferedWriter.write("luck value is : " + luck);
            bufferedWriter.newLine();
            bufferedWriter.write("figure value is : " + figure);
            bufferedWriter.newLine();
            bufferedWriter.write("agility value is : " + agility);
            bufferedWriter.newLine();
            bufferedWriter.write("intelligence value is : " + intelligence);
            bufferedWriter.newLine();

            // Always close files.
            bufferedWriter.close();
        } catch (IOException ex) {
            System.out.println("Error writing to file '" + fileName + "'");
            // Or we could just do this:
            // ex.printStackTrace();
        }

        Player p = new Player();
        String s = p.readLine();
        System.out.println(s);

        Pattern pattern = Pattern.compile("[0-9]+");
        Matcher m = pattern.matcher(s);
        while (m.find()) {
            int n = Integer.parseInt(m.group());
            arl.add(n);

        }

        p.NEWnaturalTalent = arl.indexOf(0);
        p.NEWluck=arl.indexOf(1);
        p.NEWfigure=arl.indexOf(2);
        p.NEWagility=arl.indexOf(3);

    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM