Code
import javax.swing.*;
class test7{
// data member
private int size ;
private int top ;
private Object[] stack ;
// Create Syrack [ Conatauctor ]
public test7( int size ) {
this.size = size ;
this.top = -1 ; // 0 - ( 1 ) Strat Stack Top
stack = new Object[size] ;
}
// input data to stack Object Array
public void inputStack(Object data) {
// Check top < size[size -1] of Stack
if ( top + 1 < size ){
top++ ;
stack[top] = data ;
}else{
JOptionPane.showMessageDialog( null,"The Stack is FULL" ) ;
}
}
// Removed Stack Of Memory
public Object getStack() throws Exception {
// Check Stack data ! = NULL
if ( top > -1 ) {
Object data = stack[top] ;
top-- ;
return data ;
}else{
throw new Exception( "Stuck is NULL" ) ;
}
}
public int getTop() {
return this.top ;
}
public void showStack() {
System.out.println() ;
System.out.println( "======= Data in Stack =======" ) ;
for ( int i = 0 ; i <= this.top ; i++ ) {
System.out.print( stack[i]+"\t" ) ;
}
System.out.println( "\n"+"position top="+this.top ) ;
System.out.println( "----------------------------------------------------------" ) ;
}
public static void main(String args[]) {
int size = 0 ;
// How to Create Stack ?
while( true ) {
try {
size = Integer.parseInt( JOptionPane.showInputDialog( null,"Enter a number for Create Stack size : " ) ) ;
break ;
} catch ( NumberFormatException number ) {
JOptionPane.showMessageDialog( null,"Error..."+number.getMessage() +"\nPlease enter number again." ) ;
break ;
}
} // while
// Create Stact
test7 newStack = new test7( size ) ;
System.out.println( "stack size = "+newStack.stack.length ) ;
// input data for Stack
for( int i = 0 ; i < newStack.size ; i++ ) {
try {
String item = JOptionPane.showInputDialog( null,"Enter of Stack data is"+( i+1 )+" : " ) ;
newStack.inputStack( Integer.parseInt( item ) ) ;
System.out.print( " Push:"+item ) ;
}catch( Exception e ) {
JOptionPane.showMessageDialog( null,"Error..., "+e.getMessage() ) ;
break ;
} // try
} // for
// show data in Stack
newStack.showStack() ;
// Remove data form Stack
try {
System.out.println( "pop : "+newStack.getStack() ) ;
newStack.showStack() ;
}catch( Exception e ) {
JOptionPane.showMessageDialog( null,"Error..., "+e.getMessage() ) ;
}
} // main
} // test7
แล้วถ้าผมจะเอาโค๊ดSumเพื่อที่จะรวมจำนวนทั้งหมดของStack
เช่นจำนวน 5 Stack ทั้ง 5Stack มีข้อมูล 1 2 3 4 5
แล้ว 1+2+3+4+5 = sum
แล้วถ้าผมจะเอาโค๊ดSumเพื่อที่จะรวมต้องเอาไปแทรกไว้ส่วนใหนของclass
เช่นโค๊ดsumArrayนี้
Code
/ SumArray.java
import javax.swing.*;
public class SumArray {
public static void main( String args[] )
{
int a[] = { 1, 2, 3, 4, 5};
int total = 0;
// add each element's value to total
for ( int count = 0; count < a.length; count++ )
total += a[ count ];
JOptionPane.showMessageDialog( null,
"Total of Array Elements: " + total,
"Sum the Elements of an Array",
JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 );
}
}
ปล.ขอบคุณล่วงหน้าทุกคำแนะนำครับ
Tag : - - - -