0

I'd like to exit a while loop when the user inputs the Enter/Return key.

Here's my code:

do
{
    //id=sclocal.nextInt();        
    try{
        id=sclocal.nextInt();
    }catch(InputMismatchException exception)
    {         
        System.out.println("Invalid input!");
        return;
    }

    if(listperformer.size() <= id || id < 0)
    {
        System.out.println("Invalid input!");
        return;
    }
    else
    {
        idlist.add(listperformer.get(id));
    }

}while(sclocal.nextLine().length() > 0);  //Here I want: *

*If the user does not want to input another id, they input nothing else and press "Enter" to leave this loop.

Laurel
  • 5,965
  • 14
  • 31
  • 57
Johnny
  • 146
  • 14

3 Answers3

0

If you are working with a JFrame or other swing components you can do something similar to this example.

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Test extends JFrame {
    private JPanel testPanel = new JPanel(new GridBagLayout());
    private GridBagConstraints c = new GridBagConstraints();
    private JLabel label1 = new JLabel("0");
    boolean bool = true;

    Test() {
        super("Swing Example");
        setLayout(new GridBagLayout());
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        buildGUI();
        c.weightx = 1.0;
        c.gridx = 0;
        c.gridy = 0;
        add(testPanel, c);
        pack();
        setFocusable(true);
        addKeyListener(new CustomKeyListener());
        setVisible(true);
        run();
    }

    private void buildGUI() {
        c.fill = GridBagConstraints.HORIZONTAL;
        c.gridx = 0;
        c.gridy = 0;
        testPanel.add(label1, c);
    }

    private void run() {
        int i = 0;
        do {
            i++;
            label1.setText(i+"");
            repaint();
            revalidate();
            validate();
            try {
                Thread.sleep(1000);
            } catch (Exception e) {

            }
        } while(i<100 && bool);
    }

    public static void main(String[] args) {
        new Test();
    }

    private class CustomKeyListener implements KeyListener
    {
        @Override
        public void keyPressed(KeyEvent e) {
            if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                bool = false;
            }
        }

        @Override
        public void keyReleased(KeyEvent e) {

        }

        @Override
        public void keyTyped(KeyEvent e) {

        }
    }
}

However, if you are working with command line or some other console then look at this answer. As this will allow you to check for the return key without pausing the while loop to wait for an input from the console

Community
  • 1
  • 1
Dan
  • 7,286
  • 6
  • 49
  • 114
0

The problem is what you want is a KeyListener. However, this is only available for swing classes and developing GUI applications.

In addition to this, as others have said, how could a user enter input if the 'Enter/Return' key ended the application?

So you likely would have to look at other ways of achieving this probably the best way would be do to;

Scanner scanner = new Scanner(System.in);
String userInput;
boolean quit = false;

do {
    userInput = scanner.nextLine();

    switch (userInput)
    {
        case "check1":
            System.out.println( "check 1" );
            break;
        case "check2":
            System.out.println( "check 2" );
            break;
        case "quit":
            quit = true;
            break;
        default:
            System.out.println( "Incorrect" );
            break;
    }
}while (!quit);

If you wanted to check a int user entered value then you can simply change the userInput type like so:

Scanner scanner = new Scanner(System.in);
int userInput;
boolean quit = false;

do {
    userInput = scanner.nextInt();

    switch (userInput) 
    {
        case 1:
            System.out.println("check 1");
            break;
        case 2:
            System.out.println("check 2");
            break;
        case 0:
            quit = true;
            break;
        default:
            System.out.println("Incorrect");
            break;
    }
}while (!quit);
Tom C
  • 804
  • 2
  • 11
  • 24
0

Scanner is by default using \p{javaWhitespace}+ as delimiter which means one or more whitespace but line separators like \r and \n are also considered as whitespace so for data like

1\r\n
\r\n
0\r\n

code:

int i1 = scanner.nextInt();
int i2 = scanner.nextInt();
int i3 = scanner.nextInt();

will return

1
0
..here scanner will be waiting for next integer since stream is still opened

Now problem you are facing is that nextInt() when reading data doesn't consume line separators \r \n so next call of nextLine() simply returns string which exists before scanner will be able to find these separators.
In case of this example (and probably also in case of your user input) it means that nextLine used in your while condition will always return empty string.

You could think that way to solve this problem is to simply move cursor to next line by adding nextLine after each nextInt. But it is not that easy because

  • nextInt still will be ignoring line separators since they are whitespaces, and input-stream is still opened,
  • another call of nextLine() will read entire line which for data like 1\r\n0\r\n will also consume 0.

Possible solutions:

Since nextInt will ignore any whitespace you will not be able to use this method and at the same time use empty line as representation of end of data. So you have two solutions

  1. Use predefined sequence as representation of end of input data like

    Scanner sc = new Scanner(System.in);
    System.out.println("give me id: ");
    while(!sc.hasNext("exit")){
        if (sc.hasNextInt()){
            int id = sc.nextInt();
            //handle that id
        }else{
            System.out.println("Invalid input!");
            //now either consume incorrect value to let scanner move to next one
            sc.next();
            //OR break entire loop
            //break;
            //           or method 
            //return;
        }
        System.out.println("give me id: ");
    }
    System.out.println("out of loop");
    
  2. read input line-by-line and parse it manually (I would probably avoid this solution)

    Scanner sc = new Scanner(System.in);
    String line = "";
    do {
        System.out.println("give me id: ");
        line = sc.nextLine();
        Scanner tmpScanner = new Scanner(line);
        if (tmpScanner.hasNextInt()){
            int id = tmpScanner.nextInt();
            //handle that id
        }else{
            System.out.println("Invalid input!");
            //you can let loop continue or break it by 
            // line = "";
        }
    
    } while (!line.isEmpty());
    System.out.println("out of loop");
    
Pshemo
  • 122,468
  • 25
  • 185
  • 269