-1

my code is never closing my Scanner input stream. It let's me type in stuff in the console but does not close it with enter.

    public Stack<String> einlesen(){
    Scanner sc = new Scanner(System.in);
    Stack<String> st = new Stack<>();
    //String zeichen;
    System.out.println("Bitte geben Sie einen Text ein: ");
    while (sc.hasNext()) {
        st.push(sc.next());
    }
    //sc.close();
    return st;
}

Edit:

How can I achieve, that I can type text in the console and when I hit the Enter key, it jumps back from console to my code? Like the readline() function.

Edit2:

Ok since it doesn't seem to be possible that easy with the scanner class. I will try it with the DataInputStream Class. I will try something like: first write some text in console, write that whole thing into a variable and then go through every single character in that variable. Thanks for your help though.

Quatsch
  • 361
  • 1
  • 8
  • 29

1 Answers1

2

I believe this

String zeichen;
System.out.println("Bitte geben Sie einen Text ein: ");
while (sc.hasNext()) {
  st.push(zeichen);
  zeichen = sc.next();
}

Should be something like -

// String zeichen;
System.out.println("Bitte geben Sie einen Text ein: ");
if (sc.hasNextLine()) { // <--- while to get multiple lines. if for one line.
   String str = sc.nextLine();
  // if (str.equalsIgnoreCase("quit")) { // <-- possibly, if you want multiple
  //                                     // lines.
  //   break;
  // }
  st.push(str);
}

Edit

Based on your comments, and edits - I think you really wanted a Stack<Character> (not String),

public Stack<Character> einlesen(){
    Scanner sc = new Scanner(System.in);
    Stack<Character> st = new Stack<>();
    System.out.println("Bitte geben Sie einen Text ein: ");
    if (sc.hasNextLine()) {
        String str = sc.nextLine();
        for (char ch : str.toCharArray()) {
            st.push(ch);
        }
    }
    return st;
}
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
  • 1
    It is not the perfect solution for my problem but that might also have been the fault of my english skills. Thanks a lot Elliott Frisch. – Quatsch Aug 27 '14 at 01:22