2016-04-17 6 views
-1

私は以下の2つのクラスを持っています。私はユーザの入力をコンストラクタに渡すことを考えていますか?もちろん私のコンストラクタにユーザ入力を渡すことができます

public class NewCamper { 
    String first; 
    String last; 

    public String getCamperName() { 
     return (first +" "+ last); 
    } 

    NewCamper(){ 
     first = "Ben"; 
     last = "lloyds"; 
    } 

} 
+0

なぜですか? NewCamperクラスのための1つのパラメータ化されたコンストラクタを作成します。 –

答えて

2

次のことができます。

import java.util.Scanner; 

    public class CampingSystem { 

     public static void main(String[] args) { 
      NewCamper a = new NewCamper(); 
      Scanner b = new Scanner(System.in); 

      System.out.println("Input Customer First Name"); 
      String fName = b.nextLine(); 

      System.out.println("Input Customer Surname"); 
      String lName = b.nextLine(); 


      System.out.println(a.getCamperName()); 

     } 

} 

は、それから私は、クラスとコンストラクタを持っています。必要なパラメータを受け取って使用するコンストラクタを実装し、そのコンストラクタを代わりに呼び出すだけです。やさしい。 :-)

NewCamper(String firstName, String lastName){ 
    first = firstName; 
    last = lastName; 
} 

NewCamper a = new NewCamper(fName, lName); 
+0

多くのありがとうの男 –

+1

yw、しかし、http://stackoverflow.com/help/someone-answersを読んで従ってください – Vampire

+0

完了しました、ありがとう情報 –

0

確実なこと!あなたのNewCamperクラスで

public NewCamper(String first, String last) { 
    this.first = first; 
    this.last = last; 
} 

その後CampingSystem

Scanner b = new Scanner(System.in); 
System.out.println("Input Customer First Name"); 
String fName = b.nextLine(); 

System.out.println("Input Customer Surname"); 
String lName = b.nextLine(); 

NewCamper a = newCamper(fName, lName); 

System.out.println(a.getCamperName()); 
0

コンストラクタを作成し、あなたのキャンプSystemクラスでは、あなたが次に

public class NewCamper { 
    String first; 
    String last; 

    public newCamper(String firstName, String lastName) { 
     this.first = firstName; 
     this.last = lastName; 
    } 

    public NewCamper() { 
     first = "Ben"; 
     last = "lloyds"; 
    } 
    public String getCamperName() { 
     return (first +" "+ last); 
    } 
} 

をしたいパラメータを受け取るコンストラクタを構築し、そのコンストラクタをコードで呼び出す:

NewCamper person = new NewCamper(fname,lname); 
関連する問題