一个构造函数,其参数包含字符串

时间:2016-01-06 07:51:49

标签: java

我想根据JOptionPane输入框中输入的内容为学生构造函数的参数指定字符串。我有用户输入的信息设置为变量,但当我尝试使用这些变量作为构造函数的参数时,我得到一个错误。

这是主要的

public class main {
    public static void main(String[] args) {
        String nameinput;
        String gradeinput;
        String resourceinput;
        String whatMissinginput;

        int infoComformation = 1;

        if (infoComformation == 1) {
            nameinput = JOptionPane.showInputDialog("What is the students name");
            gradeinput = JOptionPane.showInputDialog("What is the students grade");
            resourceinput = JOptionPane.showInputDialog("What resource are you pulling the child out for ");
            whatMissinginput = JOptionPane.showInputDialog("What subject are you pulling the child out of ");
            infoComformation = JOptionPane.showConfirmDialog(null,
                    "Is this the correct informtion \n " + "Name = " + nameinput + "\n" + "Grade = " + gradeinput + "\n"
                            + "Resouce = " + resourceinput + "\n" + "Subject Missing = " + whatMissinginput);
        } else if (infoComformation == 0)
        // THIS IS WHERE THE PROBLEM IS
        {
            student pupil = new student(nameinput, gradeinput, resourceinput, whatMissinginput);
        }
    }
}

这是构造函数类

import javax.swing.JOptionPane;

public class student {

    public String studentinfo(String nameinput, String gradeinput, String resourceinput, String whatMissinginput) {
        String name = "";
        String grade = "";
        String resource = "";
        String whatMissing = "";

        name = nameinput;
        grade = gradeinput;
        resource = resourceinput;
        whatMissing = whatMissinginput;

        return name + grade + resource + whatMissing;
    }
}

我该怎么办?

1 个答案:

答案 0 :(得分:0)

首先,您需要创建一个与类名相同且没有返回类型的构造函数,如

public class student {

  String name;
  String grade;
  String resource;
  String whatMissing;
  // Constructor with four parameters
  public student(String name, String grade, String resource, String whatMissing) {
    this.name = name;
    this.grade = grade;
    this.resource = resource;
    this.whatMissing = whatMissing;
  }}

在上面的代码块中,无论你传入构造函数参数,你的对象都被初始化了。之后你可以在你的方法中连接参数并返回它。 @YoungHobbit已经提到了

构造函数在内部是一个非静态方法,名称为<init>,返回类型为void。它没有返回任何东西。在内部分配第一个对象,然后调用其构造函数。对象未使用构造函数本身分配。 换句话说,语法new Object()不仅调用构造函数,还创建新对象,并在调用构造函数后返回它。太阳队&#39; Java教程代表&#34;新运算符之后是对构造函数的调用,该构造函数初始化新对象。&#34;初始化并不意味着创建。