Java 从输入打印数据结构不起作用
我试图创建一个程序,从输入中打印数据结构。输入和输出如下所示:。例如,在第一个测试用例中:第一行表示在该用例中后面将有多少行。然后,如果一行中的第一个数字是数字1,则表示要将元素添加到堆栈/队列/优先级队列,2表示要取出元素,因此一行中的第二个数字是值。然后输出打印堆栈、队列、优先级队列、不可能或不确定是否可以不止一个 这是我现在拥有的代码:Java 从输入打印数据结构不起作用,java,data-structures,stack,queue,Java,Data Structures,Stack,Queue,我试图创建一个程序,从输入中打印数据结构。输入和输出如下所示:。例如,在第一个测试用例中:第一行表示在该用例中后面将有多少行。然后,如果一行中的第一个数字是数字1,则表示要将元素添加到堆栈/队列/优先级队列,2表示要取出元素,因此一行中的第二个数字是值。然后输出打印堆栈、队列、优先级队列、不可能或不确定是否可以不止一个 这是我现在拥有的代码: import java.util.PriorityQueue; import java.util.Scanner; public class Data
import java.util.PriorityQueue;
import java.util.Scanner;
public class DataStructure {
public static void main(String[] args)
{
while(calculate());
}
private static boolean calculate()
{
Scanner input = new Scanner(System.in);
int numberOfRowsPerCase = input.nextInt();
Stack<Integer> stack = new Stack<Integer>();
Queue<Integer> queue = new Queue<Integer>();
PriorityQueue<Integer> prioQueue = new PriorityQueue<Integer>();
boolean stackBool = true;
boolean queueBool = true;
boolean prioQueueBool = true;
int next;
for(int i = 0; i < numberOfRowsPerCase; i++)
{
next = input.nextInt();
if(next == 1)
{
next = input.nextInt();
stack.push(next);
queue.enqueue(next);
prioQueue.add(next);
}
else if(next == 2)
{
next = input.nextInt();
if(!stack.pop().equals(next))
{
stackBool = false;
}
else if(!queue.dequeue().equals(next))
{
queueBool = false;
}
else if(!prioQueue.poll().equals(next))
{
prioQueueBool = false;
}
}
if(stackBool == true)
{
System.out.println("stack");
}
else if(queueBool == true)
{
System.out.println("queue");
}
else if(prioQueueBool == true)
{
System.out.println("priority queue");
}
else if((stackBool == true && queueBool == true) || (queueBool == true && prioQueueBool == true) || (stackBool == true && prioQueueBool == true))
{
System.out.println("not sure");
}
else
{
System.out.println("impossible");
}
}
//Check EOF
String in;
in = input.nextLine();
in = input.nextLine();
if(in.equals(""))
{
return false;
}
return true;
}
}
但是当我在上面的图片上运行测试用例时,我的程序打印出这样的内容:这是错误的。我找不到它为什么会这样,这里的其他人能看到吗?假设您设置布尔标志的逻辑是正确的,那么这部分
if(stackBool == true)
{
System.out.println("stack");
}
...
else if((stackBool == true && queueBool == true) || (queueBool == true && prioQueueBool == true) || (stackBool == true && prioQueueBool == true))
{
System.out.println("not sure");
}
将永远不会按预期工作,因为第二个条件的部分已被第一个条件捕获
更好的建议是提出一种更清晰的表达方式。一个可能仍然有效的建议是将更复杂的if语句放在if-else链的开头
不考虑上述假设:
if(!stack.pop().equals(next))
{
stackBool = false;
}
else if(!queue.dequeue().equals(next))
{
queueBool = false;
}
else if(!prioQueue.poll().equals(next))
{
prioQueueBool = false;
}
这些不应该是其他的,它们都是完全独立的。好吧,我只想到了布尔型的方法。没有办法改变else,如果有,那么它会工作吗?我将引用回答者的话,把你更复杂的if语句放在if-else链的开头。哦,对不起,我错过了,读得太快了。我做了改变,它打印了这个:所以没有改变。它似乎总是运行第一个if语句,所以我将它们设置为false可能是错误的。好的,还有一个问题。。。我将编辑我的答案。编辑:已更新。@user2597001已更新。这里有一条评论通知你。