shohamc1
shohamc1

Reputation: 3

How to execute Print statement after getting input from user

I have code which is:

import java.util.Scanner;
class shoham
{
    public static void main (String args[])
    {
        System.out.println("Enter your name: ");
        Scanner name = new Scanner(System.in);
        System.out.println("Your name is: ");
        System.out.print(name.nextLine());
    }
}

When I execute this command, I get output like:

Enter your name:
Your name is: 
*****                               (user input)
*****                                (output)

Can anyone give a code that gives output like:

Enter your name: **** - (user input)
Your name is: **** - (output from user input)`

Upvotes: 0

Views: 2036

Answers (5)

JNL
JNL

Reputation: 4703

You have got lot of sloutions here, but you need to know the issue with your code is,

You did not store the input from the user.

System.out.print("Enter your name: ");  
String name = name.nextLine();  // read input, store it

Upvotes: 0

Freak
Freak

Reputation: 6873

here is your code:

        System.out.println("Enter your name: ");
        Scanner name = new Scanner(System.in);
        System.out.println("Your name is: "+name.nextLine());

Upvotes: 0

Prabhaker A
Prabhaker A

Reputation: 8473

try this

public static void main (String args[])
{
    System.out.print("Enter your name: ");
    Scanner scanner = new Scanner(System.in);
    String name = scanner.nextLine()
    System.out.println("Your name is: "+name);
}

Upvotes: 0

Rahul Tripathi
Rahul Tripathi

Reputation: 172418

You may try something like this ie try using print only instead of println:-

Scanner name = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = name.nextLine();
System.out.print("Your name is: ");
System.out.println(name);

Upvotes: 0

arshajii
arshajii

Reputation: 129507

Well you're reading input after your print statements. You probably want:

Scanner in = new Scanner(System.in);  // do this first, and give it a 
                                      // better name

System.out.print("Enter your name: ");  // use print to keep it on one line
String name = in.nextLine();  // read input, store it
System.out.print("Your name is: ");
System.out.println(name);  // print name
Enter your name: Joe
Your name is: Joe

Upvotes: 1

Related Questions