有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何从新对象调用字段

我在这里创建了一个名为“Person”的类:(忽略toString。我还没有用它做任何事情)

 public class Person {
    public String firstName;
    public String middleName;
    public String lastName;
    public Person() {
        firstName = "first";
        middleName = "middle";
        lastName = "last";
    }
    public Person(String first, String middle, String last) {
        firstName = first;
        middleName = middle;
        lastName = last;
    }
    public String toString() {
        return (firstName + " " + middleName + " " + lastName);
    }
    public String getFirstName() {
        return firstName;
    }
    public String getMiddleName() {
        return middleName;
    }
    public String getLastName() {
        return lastName;
    }
}

然后我在一个新文件中创建了一个实现类,如下所示:

import java.util.*;

public class TestProgPerson
{

   static Scanner console = new Scanner(System.in);

   public static void main(String[] args)
   {

      String first;
      String middle;
      String last;

      Person name = new Person("Joe", "Smith", "Blow");

      System.out.println("Name: " + name);

      System.out.println("Please enter a last name, to check if it corresponds with the persons last name: " );
      last = console.nextLine();

      if (last == (objectReference.lastName))
      System.out.println("The last name you entered matches the persons last name");
      else
      System.out.println("The last name you entered does not match the persons last name");

    }
}

所以我想让它做的是:有一个名、中名和姓的对象。输出该名称。(到目前为止,该计划一直有效)。然后我想让用户输入姓氏,程序检查输入的姓氏是否与对象中的姓氏相同。如何仅从该对象调用单个字符串


共 (1) 个答案

  1. # 1 楼答案

    在这里,您调用的是类的name对象,而不是该类的任何字段

    System.out.println("Name: " + name);
    

    可以使用类的对象和点运算符在此处调用字段

    例如

    System.out.println("Name: " + name.firstName + " " + name.middleName  + " " + name.lastName);
    

    此外,因为字符串是Objects,应该与equals方法进行比较