简体   繁体   English

是否可以使用扫描仪输入不同对象的值?

[英]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). 它分别考虑了我的三个骑士的攻击,防御,健康和眩晕能力(动态),并将它们与拥有自己攻击和防御(静态)的boss相匹配。 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. 我为Knight和Boss的每个人定义了各自的属性,但是在主类中声明对象时,我不想硬编码其中的值,而是让用户输入自己的值来制作整个程序动态。

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. 在您的情况下,您可以在循环内调用“ nextInt()”来获取骑士所需的4个值。 (remember to also Call nextLine() to consume the enter key typed by the user). (请记住也调用nextLine()以使用用户键入的Enter键)。 When you collected 4 values, your code uses them to create a new knight object. 当您收集4个值时,您的代码将使用它们创建一个新的Knight对象。 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! 扫描程序不知道您的骑士等级,因此您只能使用它来询问创建骑士所需的int参数!

But honestly: be careful about providing such data manually. 但老实说:小心手动提供此类数据。 Do you really want to type 16 values each time you run your code? 您是否真的要在每次运行代码时键入16个值? 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 , 输入字符串,例如:“ 15346、17378、1784,.25”,然后除以,

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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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