英文:
Best practice for getting user input from multiple methods in Java?
问题
方法1:在每个方法中分别创建新的Scanner对象:
// 从用户获取日期
public static LocalDate getDateFromUser(String date_request_label){
Scanner inputScan = new Scanner (System.in);
System.out.print(date_request_label + " (YYYYMMDD): ");
String input_string = inputScan.nextLine();
// 将输入分割为年/月/日
int year = Integer.parseInt(input_string.substring(0,4));
int month = Integer.parseInt(input_string.substring(4,6));
int day = Integer.parseInt(input_string.substring(6,8));
return LocalDate.of(year,month,day);
}
方法2:在主函数中创建单个Scanner对象,然后在每个方法中调用它:
// 从用户获取日期
public static LocalDate getDateFromUser(Scanner inputScan, String date_request_label){
System.out.print(date_request_label + " (YYYYMMDD): ");
String input_string = inputScan.nextLine();
// 将输入分割为年/月/日
int year = Integer.parseInt(input_string.substring(0,4));
int month = Integer.parseInt(input_string.substring(4,6));
int day = Integer.parseInt(input_string.substring(6,8));
return LocalDate.of(year,month,day);
}
谢谢!
英文:
I have a relatively basic program in which I have several methods getting input from the user (using a Scanner object). I am looking to see which of these techniques (if either) is considered standard or best practice. Here I will use one method just as an example.
- Create a new scanner object in each method separately:
// Get date from user
public static LocalDate getDateFromUser(String date_request_label){
Scanner inputScan = new Scanner (System.in);
System.out.print(date_request_label + " (YYYYMMDD): ");
String input_string = inputScan.nextLine();
// Split input into year/month/day
int year = Integer.parseInt(input_string.substring(0,4));
int month = Integer.parseInt(input_string.substring(4,6));
int day = Integer.parseInt(input_string.substring(6,8));
return LocalDate.of(year,month,day);
}
- Create a single scanner object in main and call it in each method:
// Get date from user
public static LocalDate getDateFromUser(Scanner inputScan, String date_request_label){
System.out.print(date_request_label + " (YYYYMMDD): ");
String input_string = inputScan.nextLine();
// Split input into year/month/day
int year = Integer.parseInt(input_string.substring(0,4));
int month = Integer.parseInt(input_string.substring(4,6));
int day = Integer.parseInt(input_string.substring(6,8));
return LocalDate.of(year,month,day);
}
Thanks!
答案1
得分: 1
在我看来,只要不降低代码的可读性,重用一个对象是更可取的选择。
所以我会选择第二个选项。
英文:
IMHO reusing an object is preferable as long as it does not reduce the readability of the code.
So I'd go with option two.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论