gpt4 book ai didi

Java:空时停止输入

转载 作者:行者123 更新时间:2023-12-02 01:49:36 25 4
gpt4 key购买 nike

在我的程序中,我正在读取数字和符号,直到用户给我们空行。编辑:基本上程序应该模拟从堆栈(10个元素的数组)中添加/删除数字,并且有两个基本操作(添加:+并在下一行中删除一个数字并删除:对于每个成功添加的数字,程序应该在操作时打印:)是不可能的(超出数组范围) print: :( 对于可能的删除,打印数字;(如下)

*SAMPLE:*

INPUT:
+
1
+
2
+
3
+
4
+
5
+
6
+
7
+
8
+
9
+
0
+
1
-
-
-
-
-
-
-
-
-
-
-
OUTPUT:
:)
:)
:)
:)
:)
:)
:)
:)
:)
:)
:(
0
9
8
7
6
5
4
3
2
1
:(
import java.util.*;
public class Zadanie3 {

public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
String znak;

char helper;
int stack[]=new int[10];

int i =-1;
List<String> outcome = new ArrayList<>();


while (input.hasNext()){

znak=input.nextLine();
if(znak.isEmpty()){
break;
}

if(znak.charAt(0)=='+' && i<9){
znak=input.nextLine();
if(znak.isEmpty()){
break;
}
i++;
stack[i]=Integer.parseInt(znak);
outcome.add(":)");

}else if(znak.charAt(0)=='-' && i>=0 && i<=9){
outcome.add(String.valueOf(stack[i]));
i--;
}
else{
outcome.add(":(");

}
znak=input.nextLine();

if(znak.isEmpty()){
break;
}

if(znak.charAt(0)=='+' && i<9){
znak=input.nextLine();
if(znak.isEmpty()){
break;
}
i++;
stack[i]=Integer.parseInt(znak);
outcome.add(":)");

}else if(znak.charAt(0)=='-' && i>=0 && i<=9){
outcome.add(String.valueOf(stack[i]));

i--;

}

else{
outcome.add(":(");
}

}


for(String s: outcome) {
System.out.println(s);
}









}

}

输入空行输入后仍然没有停止 - 我尝试在 while 和 if 中使用 input.isEmpty() 但它也不起作用。(正如你所看到的,我在每次输入后添加了多个 if 语句,但不知何故它们没有当在几个值之后我给出空白空间时使用react。从 while 中删除 hasNext() 并用 isEmpty() 替换它,Equals() 给出相同的结果。)

最佳答案

为了制作小型工作示例,请考虑

Scanner input = new Scanner(System.in);

while (input.hasNextLine()){ // test for new input

String znak=input.nextLine(); // get input
if(znak.isEmpty()){ // see if empty
break;
}
System.out.println(znak);
}

关于Java:空时停止输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53185374/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com