我需要创建一个名称生成器,它使用for循环和if / else选择来生成名称。对于您输入的四个单词中的每个单词,输入将存储在单独的char []中。
我目前处于迷失状态,到目前为止,我只对下面编码,但它不用于循环或数组。
import java.util.Scanner;
public class NameGenerator
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.printf("Enter your first name: ");
String firstname = input.nextLine();
firstname = firstname.substring(0,3);
System.out.printf("Enter your last name: ");
String lastname = input.nextLine();
lastname = lastname.substring(0,2);
System.out.printf("Enter your mother's maiden name: ");
String mothersname = input.nextLine();
mothersname = mothersname.substring(0,2);
System.out.printf("Enter the name of the city in which you were born: ");
String cityname = input.nextLine();
cityname = cityname.substring(0,3);
String GenFirstName = (firstname + lastname);
String GenLastName = (mothersname + cityname);
System.out.println("May the force be with you, " + GenFirstName + " " + GenLastName );
}
}
答案 0 :(得分:0)
我不太确定你真正追求的是什么,但这就是我想出来的。
import java.util.Scanner;
public class NameGenerator
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.printf("Enter your first name: ");
char[] firstname;
firstname = input.next().toCharArray();
System.out.printf("Enter your last name: ");
char[] lastname;
lastname = input.next().toCharArray();
System.out.printf("Enter your mother's maiden name: ");
char[] mothersname;
mothersname = input.next().toCharArray();
System.out.printf("Enter the name of the city in which you were born: ");
char[] cityname;
cityname = input.next().toCharArray();
String GenFirstName = "";
String GenLastName = "";
for(int count = 0; count <= 3; count++){
GenFirstName += firstname[count];
GenLastName += mothersname[count];
}
for(int count = 0; count <= 3; count++){
GenFirstName += lastname[count];
GenLastName += cityname[count];
}
System.out.println("May the force be with you, " + GenFirstName + " " + GenLastName );
}
}
UPDATE 这是命令行参数版本。
public class NameGenerator
{
public static void main(String[] args)
{
char[] firstname;
firstname = args[0].toCharArray();
char[] lastname;
lastname = args[1].toCharArray();
char[] mothersname;
mothersname = args[2].toCharArray();
char[] cityname;
cityname = args[3].toCharArray();
String GenFirstName = "";
String GenLastName = "";
for(int count = 0; count <= 3; count++){
GenFirstName += firstname[count];
GenLastName += mothersname[count];
}
for(int count = 0; count <= 3; count++){
GenFirstName += lastname[count];
GenLastName += cityname[count];
}
System.out.println("May the force be with you, " + GenFirstName + " " + GenLastName );
}
}