java中读取输入的问题
我用java编写了一个使用内置堆栈API的程序java中读取输入的问题,java,java.util.scanner,Java,Java.util.scanner,我用java编写了一个使用内置堆栈API的程序 Stack <Integer> stack = new Stack<>(); int n = in.nextInt(); // number of instructions in.nextLine(); // code to consume \n left out after nextInt() String str=""; for(int i=0 ; i<n ; i++)
Stack <Integer> stack = new Stack<>();
int n = in.nextInt(); // number of instructions
in.nextLine(); // code to consume \n left out after nextInt()
String str="";
for(int i=0 ; i<n ; i++)
{
str = in.nextLine(); // Instructions for operations. Ex: 1) + 20 (pushes 20 to stack) 2) - (pops item)
char ch = str.charAt(0);
if(ch=='+')
stack.add(Integer.parseInt(str.substring(1).trim()));
else
System.out.println(stack.pop());
}
System.out.println(str); //statement that I wrote to debug
预期产出为:
10
1234
但程序在打印10后等待读取输入,因此输出如下所示:
10
//waiting for input now if I enter some text let's say test and hit enter, then it's printing 1234.
1234
我编写了最后一个println语句来测试我是否正在读取输入,字符串str是否为printing-test
有人能解释一下为什么会发生这种行为吗?java.util.Scanner类的nextLine()方法使这个扫描器前进到当前行,并返回被跳过的输入。此函数用于打印当前行的其余部分,并在末尾省略行分隔符
如果试图粘贴一组指令,请在该指令集的每一行之后尝试添加“\n”,否则可能会认为整个指令集只是一行
您还可以使用hasNextLine()方法测试线的感知方式 您可以签出我的代码。在这里,您可以直接将一组输入粘贴在一起,这样可以很好地工作:
public static void stackExample() throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Stack<Integer> stack = new Stack<>();
int n = Integer.parseInt(br.readLine());
String str = "";
for (int i = 0; i < n; i++) {
str = br.readLine();
//This is for handling, if there is any extra newline or a space in input
if (str.isEmpty() || str.equals(" ")) {
i--;
continue;
}
if (str.charAt(0) == '+') {
stack.add(Integer.parseInt(str.substring(1).trim()));
} else {
System.out.println(stack.pop());
}
}
}
public static void stackExample()引发IOException{
BufferedReader br=新的BufferedReader(新的InputStreamReader(System.in));
堆栈=新堆栈();
int n=Integer.parseInt(br.readLine());
字符串str=“”;
对于(int i=0;i
因为循环执行了6次?那么在10点之后,你必须继续吗?不清楚的。。。
public static void stackExample() throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Stack<Integer> stack = new Stack<>();
int n = Integer.parseInt(br.readLine());
String str = "";
for (int i = 0; i < n; i++) {
str = br.readLine();
//This is for handling, if there is any extra newline or a space in input
if (str.isEmpty() || str.equals(" ")) {
i--;
continue;
}
if (str.charAt(0) == '+') {
stack.add(Integer.parseInt(str.substring(1).trim()));
} else {
System.out.println(stack.pop());
}
}
}