2

Everytime I use this code:

import java.util.*;

public class Main{

public static void main (String args []){
System.out.println("What is your name?");
Scanner name = new Scanner (System.in);
System.out.println("Hello," + name);
}
} 

It just gives me random letters like:

Hello,java.util.Scanner[delimiters=\p{javaWhitespace}+][position=0][match valid=false][need input=false]

Please someone help.

3 Answers 3

2

Because what you are doing is actually just printing out the Scanner's toString method since in your code, the object name is actually an instance of Scanner, which is NOT a string.

You need to call the method to actually read the user input.

What you need to do is do something like this

import java.util.*;

public class Main{

public static void main (String args []){
System.out.println("What is your name?");
Scanner scanner = new Scanner (System.in);
String name = scanner.next();
System.out.println("Hello," + name);
}
} 
Sign up to request clarification or add additional context in comments.

Comments

0
Scanner name = new Scanner (System.in); 

Using this you have created an scan reference. Use this to read the name like

String str = name.next();

Read about Scanner class for more details.

Comments

0

You are printing reference of Scanner. If you want to input an integer, Write

Scanner in = new Scanner(System.in); 
int n = in.nextInt();

If you want to input a string, write

Scanner in = new Scanner(System.in); 
    String n = in.next();

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.