我似乎无法用我制作的堆栈解决这个问题。我为堆栈设置了一个大小,然后是第一个" push"总是空白的,只是越过用户输入点。然而第二次迭代停止并等待用户输入。为什么第一次迭代不会停止用户输入?怀疑for循环是错误的......也许是push方法?
import java.util.Scanner;
public class myApp
{
public static void main(String[] args)
throws stackOutOfBounds
{
//Variable declarations
Scanner kbd = new Scanner(System.in);
String name;
int maxSize;
//Prompts user to enter size of "shopping list" as well as name
System.out.println("What will be the name of your stack?");
name = kbd.nextLine();
System.out.println("How many items will you be putting on your stack?");
maxSize = kbd.nextInt();
//Sets name and size
MyStackADT Stack = new MyStackADT(name, maxSize);
System.out.println();
//prompts user to add Strings to shopping list
for(int y = 0; y <= maxSize; y++)
{
System.out.println("What will you be buying today?");
Stack.push(kbd.nextLine());
System.out.println("");
}
//Outputs shopping list
System.out.println(Stack);
//Outputs size of list
System.out.println("The size of the stack " + Stack.size());
System.out.println("The top of the stack is " + Stack.top());
}
}
然后输出看起来像这样......
What will be the name of your stack?
Monday
How many items will you be putting on your stack?
2
What will you be buying today?
What will you be buying today?
eggs
What will you be buying today?
milk
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
at MyStackADT.push(MyStackADT.java:24)
at myApp.main(myApp.java:30)
我需要改变for循环还是push方法?任何建议都会很棒。