如何在另一个类中使用一个类的字符串值?

时间:2014-10-01 04:15:28

标签: java string

我对Java非常陌生,我们将不胜感激!当我编译/运行" Driver.java"时,它会要求用户输入他们的名字。该计划应该采用的是该名称并将其传递给#34; Greeter.java"打印出最后的消息。

我试图实现一个接受字符串参数的构造函数,表示我的程序问候的人的姓名。我必须使用此参数来初始化我在" Greeter"中声明的私有实例变量。类。这就是我陷入困境的地方,但到目前为止我所拥有的是:

这是我的" Driver.java":

import java.util.Scanner;

public class Driver
{
   public static void main(String[] args)
   {
      Scanner scanner = new Scanner(System.in);
      System.out.print("What is your name? ");
      String name = scanner.nextLine();
      Greeter greeter = new Greeter(name);
      String greeting = greeter.greet();
      System.out.println(greeting);
   }
}

这是我的Greeter.java:

public class Greeter
{
   String inputName; (This is where I got stuck)

   public string greet()
   {
      return "Hello " + inputName;
   }

}

5 个答案:

答案 0 :(得分:1)

您缺少构造函数

public class Greeter
{
   String inputName; 

   public Greeter (String inputName) {
     this.inputName = inputName;
   }

   public String greet()
   {
      return "Hello " + inputName;
   }
}

答案 1 :(得分:0)

你需要创建一个构造函数来接受你在Main类中使用的参数:

public Greeter (String inputName) { // constructor with parameter that ll be called when Greeter's instance ll be created.
     this.inputName = inputName;
}

当任何地方Greeter greeter = new Greeter(字符串"); will be called then inputName`变量将被初始化。

所以每当你使用参数构造函数创建类的实例时,它都会初始化inputName变量。

public class Driver
{
   public static void main(String[] args)
   {
      Scanner scanner = new Scanner(System.in);
      System.out.print("What is your name? ");
      String name = scanner.nextLine();
      Greeter greeter = new Greeter(name);
      String greeting = greeter.greet();
      System.out.println(greeting);
   }
}

答案 2 :(得分:0)

Greeter greeter = new Greeter(name); 

要做到这一点,你需要一个构造函数,它接受String变量作为Greeter

中的输入参数
public class Greeter {
 String inputName;

 public Greeter(String inputName) { // matching constructor
    this.inputName = inputName;
 }

 public String greet() {
    return "Hello " + inputName;
 }
}

答案 3 :(得分:0)

通过以下代码

public class Greeter {

  private String name;

  public Greeter() { }

  public Greeter(String name) {
      this.name = name;
  }

  public String getName() {
      return name;
  }

  public void setName(String name) {
      this.name = name;
  }

  public String greet(){
      return "Hello "+ getName();
  }

}

public class Driver {

  public static void main(String[] args) {

      Scanner input = new Scanner(System.in);
      System.out.print("Enter your name : ");
      Greeter greeter = new Greeter(input.nextLine());
      System.out.println(greeter.greet());

  }

}

祝你好运!!!

答案 4 :(得分:-1)

改变你的Greeter课程。

public class Greeter{
   private String inputName;    

   public Greeter(){

   }

   public Greeter (String inputName) {
     this.inputName = inputName;
   }

   public String greet()
   {
      return "Hello " + inputName;
   }

}