0

これは非常に基本的な Java の質問であり、回答を得た後は自分自身を叩くように感じますが、現在プロジェクトに取り組んでおり、このメソッドを追加するよう指示されています: +createWelcomeMessage(userName:String) というメソッドを作成します。 )String[これも下線が引かれているので静的]. ユーザーが入力した名前を含め、プログラムの目的をユーザーに知らせる必要があります。これは私が得たものです:

public static String createWelcomeMessage(String UserName)
{
Scanner kb = new Scanner(System.in);
String strUserName;  // to get user's name
String strWelcome;   //listed as the return in method name

System.out.print("\nPlease enter your name: ");
strUserName=kb.nextLine();

System.out.println("Hello" + strUserName + " the purpose of this project is...");


return strWelcome;
}  //end createWelcomeMessage(string)

問題は、文字列 "strWelcome" をどうするかということです。それとも、このメソッドを呼び出すためにメインメソッドで使用するだけですか。ありがとう。

4

4 に答える 4

1

何かを返さなければならないようです。あなたのコードによると、あなたは初期化していませんstrWelcome。たぶん、メッセージ全体を返して印刷することになっているのでしょうか?

したがって、次のcreateWelcomeMessage(String userName)ように初期化します。

strWelcome = "Hello" + strUserName + " the purpose of this project is...";

次に、元のように戻ります:

return strWelcome;

次に、それを印刷するために呼び出す場所:

System.out.println(createWelcomeMessage(<put username here>));

または単に別の文字列に設定します

String str = createWelcomeMessage(<put username here>);

次に、それを印刷します。

System.out.println(str);
于 2013-10-17T04:35:21.190 に答える
0

パッケージcom.example;

java.util.Scanner をインポートします。

public class Sample { public static String createWelcomeMessage(String UserName) { Scanner kb = new Scanner(System.in); 文字列 strUserName; // ユーザー名を取得する String strWelcome = UserName; // メソッド名の return としてリストされます

System.out.print("\nPlease enter your name: ");
strUserName=kb.nextLine();

System.out.println("Hello " + strUserName + " the purpose of this project is...");


return strWelcome;
}  //end createWelcomeMessage(string)
public static void main(String[] args){
    String result = Sample.createWelcomeMessage("Sample");
    System.out.println("Value:"+result);
}

}

出力: あなたの名前を入力してください: テスト こんにちは、このプロジェクトの目的は... 値: サンプル

于 2013-10-18T05:00:16.690 に答える
0

strWelcome、私はあなたのウェルカムメッセージだと思います。だからあなたはこのようなものが欲しいです。

strWelcome = "Hello" + strUserName + " the purpose of this project is..."

return strWelcome; 

次に、ループの外側:

System.out.println(strWelcome);

をロード内に配置すると、値が返さSystem.out.println(strWelcome);れる場合に目的が果たせなくなります。Stringその後、メソッドシグネチャが返されるだけですvoid

于 2013-10-17T04:24:10.593 に答える