can somebody tell me how to create stack array in easy way and can make me and others like me easy to understand? please
Welcome to the Java Programming Forums
The professional, friendly Java community. 21,500 members and growing!
The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.
>> REGISTER NOW TO START POSTING
Members have full access to the forums. Advertisements are removed for registered users.
can somebody tell me how to create stack array in easy way and can make me and others like me easy to understand? please
anyway, im doin some home that my lecturer gave to me, so here what i done so far...
import java.util.*; public class Usestack { public static void main(String args[]){ Scanner sc; sc=new Scanner (System.in); int n; System.out.println("enter the size of stack"); n=sc.nextInt(); Stack s=new Stack(); int choice; do{ System.out.print("1. push, 2. pop, 3. display, 0. exit, enter your choice: "); choice=sc.nextInt(); switch(choice){ case 1: int value; System.out.print("enter element to push: "); value=sc.nextInt(); s.push(value); break; case 2: s.pop(); break; case 3: System.out.println(s); break; case 0: break; default:System.out.println("invalid choice"); } }while(choice!=0); } }
when i click run the program, it can be 'use', but... my lecturer said that my ARRAY size no function, that true, when i run the program the first line said "enter the size of stack", so i enter 2 or 3 size of stack, but then, the program show that i can push many element as i want, more than what i enter the size of stack, so how to do the stack size(to input)...
The Java stack class extends the Vector super class, so it will automatically expand itself when you try to add elements beyond the current size.
If you really want to limit the stack size, you need to check the size in case 1 before allowing the user to push more onto the stack:
case 1: if (s.size() < n) { // code to add new element to stack } else { System.out.println("You've reached the stack limit!"); } break;