Hello guys ;

I have a question in java . is it possible to great a method in java program that :

if ( user press "Enter" )

do some thging

I tried this simple examples , but dosn't work with me

Scannaer in  = new Sccanner (System.in ) ; 

String name  = in.next (); 

if (name.equals("")) // which I men  If user press "Enter"
System.out. println("you did not entered any name for example !! ");

// also I tryed 

 if (name.equals(null)
// or 
 //do some thing 

// but both dosn't work !!

Could any body help me how to great a method in Java

if user press "Enter "



Thank you for reading it

(1) May I ask: Why only press "return key" to do something? You may do something when receiving other input string.
(2) One class may implement the interface KeyListener to listening to the keyboard.
(3) I have written a simple program using KeyAdapter to monitor the keyboard for your reference.

/* The following program is listening to the kayboard.
 * DOS window output prints each character client pressed. 
 * When pressing return key, "Do Something" is printed.
 * */
import java.awt.event.*;
import javax.swing.*;

public class Key extends JFrame{
	public Key(){
	addKeyListener(new KeyAdapter(){  //anonymous class			
	public void keyPressed(KeyEvent e){ //call this method by pressing any key
	System.out.println(e.getKeyChar());	// print any printable character
	if ((int)e.getKeyChar()==10) // if pressing the "return key"
		System.out.println("Do Something");// then print "Do Something"
	public static void main(String args[]){
		Key k = new Key();

If you're using the console, you're on the right track. Your only trouble is that the Scanner.next() method only seems to grab non-null input followed by a return. Just the return won't do it. Try Scanner.nextLine()

Tong's solution is worth understanding when you get into a GUI, but it looks like you're not quite doing that here.


many thanks
Your explaining is helpfull for understanding how to make it In gui.


Thank you so much man . That's what I want and looking for

I tryed Scanner with nextLIne () and defiantly work