简体   繁体   English

使用扫描仪在构造函数中调用 set 方法

[英]invoke set method in constructor with scanner

I am trying to invoke a set method in a constructor that accepts user input to instantiate an object.我试图在接受用户输入以实例化对象的构造函数中调用 set 方法。 A sample of a set method is as follows: set 方法的示例如下:

public void setName(String name) {
    if(name.length()>0 && name.length()<25) {
        this.name = name;
    }
    else {System.out.println("Name length can not exceed 25 characters.");}
}

I then want to accept the user input to instantiate the object.然后我想接受用户输入来实例化对象。 I currently have it formatted like so:我目前的格式如下:

public Character(String name){ name = setName(input.nextLine());}

I have imported the scanner and created a scanner object.我已经导入了扫描仪并创建了一个扫描仪对象。 The character constructor itself is actually quite large, it consists of 29 variables, each of which have a set method similar to the first code sample.字符构造器本身其实很大,它由29个变量组成,每个变量都有一个类似于第一个代码示例的set方法。

My ultimate goal is to put this in a GUI form for a person to fill out.我的最终目标是将它放在一个 GUI 表单中供人们填写。 The error Eclipse gives for my current syntax is "type mismatch, cannot convert from void to String". Eclipse 为我当前的语法给出的错误是“类型不匹配,无法从 void 转换为字符串”。

How is this supposed to be done?这应该怎么做?

The easiest approach is to modify your code like this:最简单的方法是像这样修改你的代码:

public String setName(String name) {
    if(name.length()>0 && name.length()<25) {
        this.name = name;
    }
    else {System.out.println("Name length can not exceed 25 characters.");}
    return name;
}

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

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