import java.util.Scanner;
import javax.swing.JOptionPane;
public class StarWars {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
String firstName = "";
String lastName = "";
String maidenName = "";
String town = "";
System.out.print("What is your first name? ");
firstName = reader.nextLine();
System.out.print("What is your last name? ");
lastName = reader.nextLine();
System.out.print("What is your mothers maiden name? ");
maidenName = reader.nextLine();
System.out.print("What town were you born? ");
town = reader.nextLine();
String Sfirstname = firstName.substring(0,2);
String Slastname = lastName.substring(0,3);
String SmaidenName = maidenName.substring(0,2);
String Stown = town.substring(0,3);
String Star = Sfirstname + Slastname;
String War = SmaidenName + Stown;
String StarWar = Star + War;
System.out.print("Your Star Wars name is: " + StarWar);
}
public static String StarWar (String Star, String War) {
String name;
name = Star + " " + War;
return War;
}
}
这是我关于我的项目的代码。当我做我的项目时,我对返回方法和传递方法有一些问题。
我完美地设置了 main 方法来打印出我想看到的东西。
问题是我还必须使用传递方法和返回方法。我的老师希望我通过传递/返回方法做两件事。
- 将所有这些数据传递给您的方法,该方法应生成并返回用户的星球大战名称。
- 获取方法的返回值,并将其显示到屏幕上。
我不知道我应该如何解决这个问题(花了 5 个小时完成我学到的所有事情,但都是错误的......)。
有人可以给我提示或教我老师实际上希望我做什么以及我该如何做到这一点吗?
我真的需要你们的帮助。
另外,如果我运行一个程序,它应该是这样的。
名字?用户输入:Alice 姓氏?用户输入:史密斯母亲的婚前姓名?用户输入:你出生在马塔镇吗?用户输入:萨克拉门托
你的星球大战名字是:SmiAl MaSac
最佳答案
这里有一些我们可以改进的地方,让我们从方法开始 - 方法名称看起来像一个构造函数,本身并不执行逻辑,让我们描述它的作用并将逻辑移到方法中 - 我们不这样做不需要所有这些临时变量(我们可以使用 StringBuilder
),例如
public static String buildStarWarsName(String firstName, String lastName,
String maidenName, String town)
{
return new StringBuilder(lastName.substring(0, 3)) //
.append(firstName.substring(0, 2)) //
.append(" ") // <-- for the space between first and last
.append(maidenName.substring(0, 2)) //
.append(town.substring(0, 3)) //
.toString();
}
然后你可以在读取变量时初始化它们并最终调用该方法
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.print("What is your first name? ");
String firstName = reader.nextLine();
System.out.print("What is your last name? ");
String lastName = reader.nextLine();
System.out.print("What is your mothers maiden name? ");
String maidenName = reader.nextLine();
System.out.print("What town were you born? ");
String town = reader.nextLine();
System.out.print("Your Star Wars name is: " + //
buildStarWarsName(firstName, lastName, maidenName, town));
}
关于Java如何传递和返回字符串、方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46556154/