在 stackoverflow 和其他论坛上寻找解决方案一个小时后,我放弃了。
您知道我为什么会遇到异常吗?
public Stack<Character> einlesen(){
Scanner sc = new Scanner(System.in);
Stack<Character> st = new Stack<>();
System.out.println("Please insert any random text: \n");
DataInputStream is = new DataInputStream(System.in);
try {
String eingabe;
eingabe = is.readLine();
int i = 0;
while (eingabe.charAt(i) != -1 ) {
st.push(eingabe.charAt(i));
i++;
}
} catch (IOException e) {
e.printStackTrace();
}
return st;
编辑:
感谢 Elliot,它运行得非常完美。
如果我现在想以相反的顺序重写堆栈中的所有字符,我尝试使用以下代码。但只写了几个字。当我使用查看功能时,它会提供所有这些信息。
所以我猜“我”有问题
for ( int i =0; i<st.size();i++) {
System.out.print(st.pop().toString());
}
最佳答案
Do you have an idea why I am getting the exception?
是的...
您的 eingabe
字符串不可能包含等于 -1
的字符。 (甚至字符 0xffff
也会转换为整数 65535
。)因此,您的 while 循环只是简单地从字符串末尾建立索引。
(Java 字符串无论如何都不会以任何特定字符终止。Java 不是 C 或 C++。)
使用eingabe.length()
告诉您何时停止...
After an hour of looking for an solution in stackoverflow and other forums I gave up.
这里有一些免费建议:
您所做的不是解决程序问题的正确方法。正确的编程方法是根据您对 Java 语言和类库的了解来阅读和理解您的代码。如果您还没有这些知识......
学习 Oracle Java 教程,或者购买并阅读一本优秀的 Java 初学者教科书。
阅读您尝试使用的类的 javadoc。
在谷歌上搜索简单编程问题的解决方案可能是浪费时间。您不会学到很多东西,而且很有可能会找到不正确或不适当的解决方案,和/或当您看到正确的解决方案时您将无法识别它们。
关于java - StringIndexOutOfBoundsException while 循环与charat(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25518066/