是否可以让用户在一个方法中输入他们的第一个,中间名和姓,然后返回所有字段?
import java.util.Scanner;
public class name {
// firstName middleInitial and lastName
// toUpperCase for names
String firstName, midddleInitial, lastName;
public name(String firstName, String middleInitial, String lastName) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter First Name:");
String firstName = scanner.nextLine();
System.out.println("Enter Middle Initial:");
System.out.println("Enter Last Name:");
return firstName;
return middleInital;
return lastName;
}
} // end of name class
答案 0 :(得分:1)
您只能从方法中返回一件事。但你可以做这样的事情:
String firstName, midddleInitial, lastName;
public void inputName() {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter First Name:");
firstName = scanner.nextLine();
System.out.println("Enter Middle Initial:");
midddleInitial = scanner.nextLine();
System.out.println("Enter Last Name:");
lastName = scanner.nextLine();
}
该方法什么都不返回。但是,名称现在将在类级变量中,这些变量可以在整个类中访问。
答案 1 :(得分:0)
您可以执行以下操作,迭代调用该方法以获得答案。让我知道你想通过你的代码实现什么,所以我可以相应地调整它。 你可以尝试递归地将它放在你自己的方法中,这是你想要实现的,我猜想。
static String firstName;
static String middleInitial;
static String lastName;
private static int i;
public static String name() {
System.out.print("i"+i);
if(i==1)
{Scanner scanner =new Scanner(System.in);
System.out.println("Enter First Name:");
firstName = scanner.nextLine();
return firstName;
}
else if(i==2)
{
Scanner scanner =new Scanner(System.in);
System.out.println("Enter Middle Name:");
middleInitial = scanner.nextLine();
return middleInitial;
}
else
{
Scanner scanner =new Scanner(System.in);
System.out.println("Enter Last Name:");
lastName = scanner.nextLine();
return lastName;
}
}
public static void main(String[] args)
{
i=1;
if(i==1)
{
String name1=name();
System.out.print("1"+name1);
i=2;
}
if(i==2)
{
String name2=name();
System.out.print("2"+name2);
i=3;
}
if(i==3)
{
String name3=name();
System.out.print("3"+name3);
}
}