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;
}
}
所以这是我的项目代码。当我正在做我的项目时,我对返回方法和传递方法有一些问题。
我完美地设置了主要方法来打印出我想要看的东西。
问题是我还必须使用传递方法和返回方法。我的老师要我用传递/返回方法做两件事。
我不知道我应该怎么处理这个问题(用了5个小时来做我学到的所有事情但错了......)。
有人可以暗示或教我实际上老师要我做什么以及我该怎么做?
我真的需要你们的帮助。
另外,如果我运行程序,它应该是这样的。
名字?用户输入:爱丽丝姓氏?用户输入:史密斯母亲的娘家姓?用户输入:你出生的马塔镇?用户输入:萨克拉门托
您的星球大战名称是:SmiAl MaSac
答案 0 :(得分:0)
您应该返回您评估的内容:
return name;
然后在想要读取值时调用此定义的方法。
评论中突出显示的更改:
String StarWar = Star + War; // this would not be required, as handled by your method 'starWarName'
System.out.print("Your Star Wars name is: " + starWarName()); // calling the method defined
}
public static String starWarName (String Star, String War) { //renamed method to break the similarity with other variables
String name;
name = Star + " " + War;
return name; //returning the complete star war name
}
答案 1 :(得分:0)
你的方法正在回归战争'参数。根据您的尝试,它看起来应该返回' name'。这就是方法的构建方式。
答案 2 :(得分:0)
我们可以在这里改进一些东西,让我们从方法开始 - 方法名称看起来像构造函数,并且不执行逻辑本身,让我们描述它的作用并将逻辑移动到方法中 - 我们不要不需要所有这些临时变量(我们可以使用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));
}