简体   繁体   中英

Is it possible to use a Scanner to input values for different objects?

I am building my first program to calculate the damage dealt against a boss in a mobile game. It takes into account each of my three knight's attack, defense, health, and stun capabilities (dynamic) respectively, and matches them up against a boss with their own attack and defense (static). I have separate classes for each the Knight and Boss defining their attributes, but when I am declaring the objects in the main class I'd rather not hard code the values in, but rather have the user input their own values to make the whole program dynamic.

I am unsure how I would utilize a Scanner for this particular task.

Knight knight1 = new Knight(15346, 17378, 1784, .25);

Knight knight2 = new Knight(13340, 15794, 1409, .25);

Knight knight3 = new Knight(13704, 15345, 1588, .25);

A Scanner allows you to fetch values from an input source. Could be user input, but also content from a file.

The scanner has interfaces that return values of different built-in types, depending on the content found in "scanned" source. In your case, you could call "nextInt()" within a loop to fetch the 4 values you need for a knight. (remember to also Call nextLine() to consume the enter key typed by the user). When you collected 4 values, your code uses them to create a new knight object. The scanner does not know your knight class, therefore you can only use it to ask for the int parameters you need to create knights!

But honestly: be careful about providing such data manually. Do you really want to type 16 values each time you run your code? So consider to write code that allows to quickly fetch such data, for example by using a configuration file.

input string line like: "15346, 17378, 1784, .25" and then split by ,

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    String line = in.nextLine();
    String[] lineArray = line.split(",");
    double param0=Double.parseDouble(lineArray[0]);
    double param1=Double.parseDouble(lineArray[1]);
    double param2=Double.parseDouble(lineArray[2]);
    double param3=Double.parseDouble(lineArray[3]);

    Knight knight1 = new Knight(param0, param1, param2, param3);
}

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