英文:
How do I call a string method twice in Java without repeating the whole method?
问题
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 + "!");
}
}
英文:
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 + "!");
}
}
答案1
得分: 2
如果您想要调用一个函数两次,那么我建议该函数返回用户输入并接收问题文本。您的代码似乎是正确的。
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("请输入您的名字:");
String surName = getUserInput("请输入您的姓氏:");
System.out.println(String.format("你好,%s %s!", name , surName));
}
}
英文:
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));
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论