Zach Beck
Zach Beck

Reputation: 51

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 + "!");
  }
}

Upvotes: 0

Views: 556

Answers (1)

Francisco Valle
Francisco Valle

Reputation: 643

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));
  }
}

Upvotes: 2

Related Questions