0
public static void main(String[] args) {


    // Create a usable instance of an input device
    Scanner sc = new Scanner(System.in);
    // Prompt user for input
    System.out.println("Please enter you first name:");
    // Capture first word and assign it to A Variable
    String firstName;
    firstName = sc.next();
    //Construct the greeting
    System.out.println("Hello, " + sc.next() + "!");

I am able to output the name on the screen but I have to type it in twice. I believe it is due to the sc.next statement but I am not for certain.

4 Answers4

0

Yes, it is due to the sc.next() because you are doing it twice. Change your last line to

System.out.println("Hello, " + firstName + "!");
Arthur Attout
  • 2,037
  • 1
  • 20
  • 39
0

use

System.out.println("Hello, " + firstName + "!");

after first sc.next() it's empty (also look nextLine)

Gwiazdek
  • 139
  • 8
0

The problem is that you call sc.next() twice:

    firstName = sc.next(); // 1st time
    //Construct the greeting
    System.out.println("Hello, " + sc.next() + "!"); //2nd time

Please use the assigned variable firstnameinstead:

    firstName = sc.next();
    //Construct the greeting
    System.out.println("Hello, " + firstName + "!");

This should fix you issue.

Alexander
  • 2,449
  • 3
  • 27
  • 31
0

System asks you to enter 'first name' for 2 times because you calling sc.next() for two times. To prevent this you can do it this way:

...
//Construct the greeting
System.out.println("Hello, " + firstName + "!");
...

or even this way, if you will not use String firstName in the future:

...
System.out.println("Please enter you first name:");
//Construct the greeting
System.out.println("Hello, " + sc.next() + "!");
...

I will also prefer to use nextLint() instead of next() because it automatically moves the scanner down after returning the current line. If you interested you can take a look here: https://stackoverflow.com/a/22458766/8913124

Andrij
  • 131
  • 1
  • 5