打印堆栈时java输出错误
我正在学习java,我已经编写了一个堆栈程序(LIFO)。 代码的目的是从键盘读取整数并构建堆栈
class StackDemo
{
public static void main(String[] arg)
throws java.io.IOException{
Stack s1 = new Stack();
char ch1;
System.out.println("would you like to push data into stack??? Enter y for yes. Enter n for no");
ch1 = (char) System.in.read();
if(ch1 == 'y')
{
for(int i=0; i<10; i++)
{
int input;
System.out.println("Enter an integer to push to the stack");
input = (int)System.in.read();
s1.push(input);
}
}
else if(ch1 == 'n')
{
}
else
{
System.out.println("push - Enter a valid input");
}
}
}
当我运行程序时,控制台上会显示以下结果
----------------------------------------------------------------------------
D:\personal\learn_social\Java\Complete_reference\Programs>java StackDemo
would you like to push data into stack??? Enter y for yes. Enter n for no
y
Enter an integer to push to the stack
Value is pushed onto stack successfully
Enter an integer to push to the stack
Value is pushed onto stack successfully
Enter an integer to push to the stack
----------------------------------------------------------------------------
但预期的结果是
-------------------------------------------------------------------------
D:\personal\learn_social\Java\Complete_reference\Programs>java StackDemo
would you like to push data into stack??? Enter y for yes. Enter n for no
y
Enter an integer to push to the stack
-------------------------------------------------------------------------
有人能帮助解决代码中的问题吗
提前感谢,, 尼希尔S
# 1 楼答案
您正面临这个问题,因为您直接使用
System.in
输入流来读取输入。它并没有按你所希望的方式工作。您会得到多个输入,因为System.in
会将您在按“y”后输入的新行[Enter]也视为输入。使用System.in
的一种方法是将其包装在Scanner
中,如下所示:或者,您可以使用
BufferedReader
而不是Scanner
。你应该从文档中了解更多。你可以找到描述here和here。希望这有帮助# 2 楼答案
使用
Scanner
表示int值# 3 楼答案
问题是,当您键入“y”并按Enter键时,实际上输入了3个字符:y、\r、\n(13个墨盒返回和10个换行)。使用上述方法之一可以避免该问题。我会用#法佐夫斯基写的那本书,因为它更简单
# 4 楼答案
例如:System.in.read() does not read
您需要使用Scanner类。可以像这样实例化scanner对象
然后使用
# 5 楼答案
我建议你定义一个读者对象。在代码中,可能会出现错误,因为一行中有两个“read.In”操作没有关闭该读卡器。以下是示例: