[英]How do I call a string method twice in Java without repeating the whole method?
What I am trying to do is prompt a user to enter their first and last name by calling a function twice.我想要做的是通过两次调用函数来提示用户输入他们的名字和姓氏。 First call would be for the first name and the second call would be for the last name.
第一个电话是名字,第二个电话是姓氏。 The program would then concatenate and display "Hello, firstname lastname!"
然后程序将连接并显示“你好,名字姓氏!” I feel like I am very close to the correct outcome but I am obviously missing something.
我觉得我非常接近正确的结果,但我显然错过了一些东西。 New guy here.
新人来了Thank you for any and all responses.
感谢您的任何回复。
import java.util.Scanner;
public class firstLastName2 {
static String F_NAME;
static String L_NAME;
static String name;
static void firstName(String name) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter your first name.");
F_NAME = keyboard.nextLine();
System.out.println("Please enter your last name.");
L_NAME = keyboard.nextLine();
}
public static void main(String[] args) {
firstName(name);
System.out.println("Hello, " + F_NAME + " " + L_NAME + "!");
}
}
If you want to call a function twice, then i suggest that the function return the user input and receive the question text.如果你想调用一个函数两次,那么我建议该函数返回用户输入并接收问题文本。 Your code seem to be right.
您的代码似乎是正确的。
import java.util.Scanner;
public class firstLastName2 {
static Scanner keyboard = new Scanner(System.in);
static String getUserInput(String question) {
System.out.println(question);
return keyboard.nextLine();
}
public static void main(String[] args) {
String name = getUserInput("Please enter your first name.");
String sunrName = getUserInput("Please enter your last name.");
System.out.println(String.format("Hello, %s %s!", name , surName));
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.