为什么在代码未放入主块时抛出错误

时间:2014-09-17 06:00:21

标签: java

我正在实现一个堆栈 这是我的代码 package data_structure;

public class Stack
 { 
  private int top;
  private int max;
  private int[] data;
  Stack(int s)
   {
     max=s;
     data=new int[s];
     top=-1;
   }
  public void push(int a)
    {
     data[++top]=a;
    }
  public int pop()
    {
     return data[top--];
    }
  public int peek()
   {
    return data[top];     
   }
  public boolean isEmpty()
   { 
    if (top==-1)
    return true;
    else
    return false;
   }
 }

我正在使用另一个类

package data_structure; 
class StackImplementation 
 {

    Stack abc =new Stack(5);
    boolean value = abc.isEmpty();
    if(value==true)
      {
         System.out.println("Yes it's empty");
      }
    abc.push(22);
    abc.push(23);
  }

堆栈实现在if(value == true)处抛出类似Illegal start of type的编译错误 期望在(value == true)的标识符以及如果整个代码放在main方法下则删除的更多错误。

2 个答案:

答案 0 :(得分:3)

出现此错误的原因仅仅是因为您没有将代码包装在方法中。

if(value==true)

此时编译器并不期望if语句。

class StackImplementation {
  public void foo () {
    Stack abc =new Stack(5);
    boolean value = abc.isEmpty();
    if(value)
      {
         System.out.println("Yes it's empty");
      }
    abc.push(22);
    abc.push(23);
 }
}

请注意,您也可以跳过条件中的== true部分,因为您已经拥有boolean

答案 1 :(得分:0)

您的if声明和abc.push(22);abc.push(23);必须在方法中。如果您不想创建该方法,请使用像这样的块

class StackImplementation 
 {

    Stack abc =new Stack(5);
     boolean value = abc.isEmpty();
     {
         if(value==true)
         {
             System.out.println("Yes it's empty");
         }
         abc.push(22);
         abc.push(23);
     }

  }