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.
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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.