Java:erreur de stack

domxaline -  
 domxaline -
Bonjour,
programme suivant en executant me donne erreur aidez moi svp
import java.util.Stack;
public class Autounboxex 
{
 public static void main(String[]args)
 { 
	Stack<Integer> MyStack=new Stack<Integer>();
	MyStack.push(10);
	MyStack.push(20);
	int stackSum=MyStack.pop()+MyStack.pop();
        System.out.println("The top most element from the stack is :"+MyStack.pop());
	System.out.println("The next to top most element from the stack is :"+MyStack.pop());
	System.out.println("The sum of two element from the stack is :"+stackSum);
 }
}

erreur est suivant:
Exception in thread "main" java.util.EmptyStackException
at java.util.Stack.peek(Unknown Source)
at java.util.Stack.pop(Unknown Source)
at Autounboxex.main(Autounboxex.java:10)

A voir également:

20 réponses

tiouil
 
Attention. Stack.pop() enlève de la pile donc vu que tu ajoutes 10 puis 20 à ta pile , et que tu les enlèves pour les additionner, quand tu veux afficher ta première phrase, il n'y a plus rien.
0
tiouil
 
Fait un Stack.peek() pour regarder le sommet sans le supprimer
0
domxaline
 
System.out.println("The top most element from the stack is :"+MyStack.peek());

j'ai erreur suivante
Exception in thread "main" java.util.EmptyStackException
at java.util.Stack.peek(Unknown Source)
at Autounboxex.main(Autounboxex.java:10)
0
domxaline
 
import java.util.Stack;
public class Autounboxex 
{
 public static void main(String[]args)
 { 
	Stack<Integer> MyStack=new Stack<Integer>();
	MyStack.push(10);//autobox
	MyStack.push(20);//autobox
	//int stackSum=MyStack.pop()+MyStack.pop();//unboxing
	int stackSum=MyStack.peek()+MyStack.peek();
    System.out.println("The top most element from the stack is :"+MyStack.pop());
	System.out.println("The next to top most element from the stack is :"+MyStack.pop());
	System.out.println("The sum of two element from the stack is :"+stackSum);
 }
}

en écrivant le code comme ça,mon resultat est faux

The top most element from the stack is :20
The next to top most element from the stack is :10
The sum of two element from the stack is :40

au lieu de 30 j'ai 40 est ce normal
0
tiouil
 
Normal, regardes :
Stack<Integer> MyStack=new Stack<Integer>();
MyStack.push(10); // 1 element dans la pile
MyStack.push(20); //2 elements dans la pile
int stackSum=MyStack.pop()+MyStack.pop(); // 0 éléments dans la pile
System.out.println("The top most element from the stack is :"+MyStack.pop()); //Et la tu veux regarder quoi ??? Y'a plus rien !


Tu as plusieurs solutions :
MyStack.push(10); // 1 element dans la pile
MyStack.push(20); //2 elements dans la pile
int stackSum=MyStack.peek()+MyStack.peek(); // 0 éléments dans la pile
System.out.println("The top most element from the stack is :"+MyStack.pop()); 

Et il te resteras 1 element dans la pile (le 10)

Soit
MyStack.push(10); // 1 element dans la pile
MyStack.push(20); //2 elements dans la pile
int stackSum=MyStack.peek()+MyStack.peek(); // 0 éléments dans la pile
System.out.println("The top most element from the stack is :"+MyStack.pop());
MyStack.pop() 

Et la la pile est vide.

Sinon je te conseilles d'utiliser les Try... Catch... pour eviter de couper ton programme et juste montrer qu'il y a eu un bug en mettant :
System.out.println("Attention la pile est vide");
0

Vous n’avez pas trouvé la réponse que vous recherchez ?

Posez votre question
tiouil
 
Effectivement 10 + 20 = 30 et non 40.
(Comme quoi rien ne remplacera l'être humain ^^)

Essaies d'initialiser stackSum à 0;
Fait ca :
int stackSum=0;
stackSum = MyStack.pop();
stackSum += MyStack.pop();


au lieu de ca (on ne sait jamais un jour ca a buggé bêtement pour ca:
int stackSum=MyStack.pop()+MyStack.pop();
0
tiouil
 
Je suis bete.
J'ai trouvé.
Regardes :
Stack<Integer> MyStack=new Stack<Integer>();
MyStack.push(10);
MyStack.push(20);// Ordre de la pile 20 puis 10
int stackSum=MyStack.peek()+MyStack.peek();// La tu additionne le sommet avec le sommet ! 20 +20 = 40.


Donc fait ca et tout ira bien :
import java.util.Stack;
public class Autounboxex 
{
 public static void main(String[]args)
 { 
	Stack<Integer> MyStack=new Stack<Integer>();
	MyStack.push(10);
	MyStack.push(20);

        int ancienSommet = MyStack.pop();
	int stackSum=MyStack.peek()+ ancienSommet;
        MyStack.push(ancienSommet);

        System.out.println("The top most element from the stack is :"+MyStack.pop());
	System.out.println("The next to top most element from the stack is :"+MyStack.pop());
	System.out.println("The sum of two element from the stack is :"+stackSum);
        System.out.println("Merci Tiouil !!!");

//Attention à la fin de ton programme il n'y a plus rien dans la pile

 }
}
0
tiouil
 
J'ai remarqué que tu as une autre question en suspend sur ton fameux triangle de chiffres équilatéral.
Je te donne la réponse en java (vu qu'ici c'est aussi un sujet java):
int main()
{
    int tailleX = 14, tailleY = tailleX/2;
    int milieu = tailleX/2;
    int min, max;
    int i, j;

    for(j = 1; j <= (tailleX/2); j++)//Ordonnees
    {
        min = milieu - (j-1);
        max = milieu + (j-1);
        for(i = 1; i <= tailleX; i++)//Abscisses
        {
            if((i>=min) && (i<=max) && ((i%2) == (j%2)))//(i%2) == (j%2) pour que le numéro de colonne soit pair quand j est paire et inversement -> n%2 retourne 0 si paire et 1 sinon
               System.out.println("j");
            else
                System.out.println(" ");
        }
        System.out.println("\n");
    }
    return 0;
}
0
domxaline
 
premier prg ok;merci beaucoup

pour le prg triangle équilatéral marche pas
résultat s'affiche comme suivant:il donne plusieurs lignes espaces
pour afficher l'autres lignes

j

j
j

j
j
j
0
tiouil
 
Je l'ai codé en c++ et au moment de la migration vers java j'ai fait une bourde :
essaies ca : chez moi ca fonctionne parfaitement :
    int tailleX = 14, tailleY = tailleX/2; 
    int milieu = tailleX/2; 
    int min, max; 
    int i, j; 

    for(j = 1; j <= (tailleY); j++)//Ordonnees 
    { 
        min = milieu - (j-1); 
        max = milieu + (j-1); 
        for(i = 1; i <= tailleX; i++)//Abscisses 
        { 
            if((i>=min) && (i<=max) && ((i%2) == (j%2)))//(i%2) == (j%2) pour que le numéro de colonne soit pair quand j est paire et inversement -> n%2 retourne 0 si paire et 1 sinon 
                System.out.println(j); 
            else 
                System.out.println(" "); 
        } 
         System.out.println("\n"); 
    } 
0
domxaline
 
public class TrinangleTest 
{
  public static void main(String[]args)
  {
	  int tailleX = 14, tailleY = tailleX/2; 
	    int milieu = tailleX/2; 
	    int min, max; 
	    int i, j; 

	    for(j = 1; j <= (tailleY); j++)//Ordonnees 
	    { 
	        min = milieu - (j-1); 
	        max = milieu + (j-1); 
	        for(i = 1; i <= tailleX; i++)//Abscisses 
	        { 
	            if((i>=min) && (i<=max) && ((i%2) == (j%2)))//(i%2) == (j%2) pour que le numéro de colonne soit pair quand j est paire et inversement -> n%2 retourne 0 si paire et 1 sinon 
	                System.out.print(j); 
	            else 
	                System.out.println(" "); 
	        } 
	         System.out.print("\n"); 
	    } 
	}
  }

resultat est suivant:

1

2
2

3
3
3

4
4
4
4
ainsi de suite
0
tiouil
 
Fait des println au lieux de print tout court.
Ce qui est drôle c'est qu'en c++ ca fonctionne parfaitement.
Peux-tu le tester en c++ ?
Si tu ne peux pas, enlèves le dernier System.out.println("\n");
0
domxaline
 
public class TrinangleTest  
{ 
  public static void main(String[]args) 
  { 
   int tailleX = 14, tailleY = tailleX/2;  
     int milieu = tailleX/2;  
     int min, max;  
     int i, j;  

     for(j = 1; j <= (tailleY); j++)//Ordonnees  
     {  
         min = milieu - (j-1);  
         max = milieu + (j-1);  
         for(i = 1; i <= tailleX; i++)//Abscisses  
         {  
             if((i>=min) && (i<=max) && ((i%2) == (j%2)))//(i%2) == (j%2) pour que le numéro de colonne soit pair quand j est paire et inversement -> n%2 retourne 0 si paire et 1 sinon  
                 System.out.print(j);  
             else  
                 System.out.print(" ");  
         }  
          //System.out.print("\n");  
     }  
 } 
  } 

resultat est suivant
1 2 2 3 3 3 4 4 4 4 5 5 5 5 5 6 6 6 6 6 6 7 7 7 7 7 7 7
entre les chiffres il y espace 3 ou 4 en appuyant sur valider pour envoyer le message tous regroupent ensemble
Ce qui est drôle c'est qu'en c++ ca fonctionne parfaitement. 
Peux-tu le tester en c++ ?  

je n'ai jamais essayer ces language
0
tiouil
 
C'est quand même pas normal : soit il fait 136 retours à la ligne, soit il en fait plus du tout en commentant ou non le
print("\n");

Je ne sais pas si tu as remarqué, mais quand tu ne commentes pas cette fameuse ligne, il fait en sorte d'écrire toujours 14 lignes (1 chiffre et 13 retours à la ligne, 2 chiffres et 12 retours à la ligne, ...)

Ensuite c'est l'inverse que je t'ai demandé, changes tout en
"System.out.prinln()"


Et laisses commenté le
\n
je pense que ça va fonctionner.
0
domxaline
 
for(i = 1; i <= tailleX; i++)//Abscisses 
	        { 
	            if((i>=min) && (i<=max) && ((i%2) == (j%2)))//(i%2) == (j%2) pour que le numéro de colonne soit pair quand j est paire et inversement -> n%2 retourne 0 si paire et 1 sinon 
	                System.out.println(j); 
	            else 
	                System.out.println(" "); 
	        } 
	         System.out.print("\n"); 

maintenant résultat suivant

1

2

2

3

3

3

4

4

4

4
0
tiouil
 
Commentes le "\n"
0
domxaline
 
Commentes le "\n"

non compris
0
tiouil
 
<code>
public class TrinangleTest
{
public static void main(String[]args)
{
int tailleX = 14, tailleY = tailleX/2;
int milieu = tailleX/2;
int min, max;
int i, j;

for(j = 1; j <= (tailleY); j++)//Ordonnees
{
min = milieu - (j-1);
max = milieu + (j-1);
for(i = 1; i <= tailleX; i++)//Abscisses
{
if((i>=min) && (i<=max) && ((i%2) == (j%2)))//(i%2) == (j%2) pour que le numéro de colonne soit pair quand j est paire et inversement -> n%2 retourne 0 si paire et 1 sinon
System.out.println(j);
else
System.out.println(" ");
}
//System.out.println("\n");
}
}
}
0
domxaline
 
rien à changer on a perdu quelque lignes c'est tout
0
tiouil
 
et ca :
public class TrinangleTest  
{ 
  public static void main(String[]args) 
  { 
   int tailleX = 14, tailleY = tailleX/2;  
     int milieu = tailleX/2;  
     int min, max;  
     int i, j;  

     for(j = 1; j <= (tailleY); j++)//Ordonnees  
     {  
         min = milieu - (j-1);  
         max = milieu + (j-1);  
         for(i = 1; i <= tailleX; i++)//Abscisses  
         {  
             if((i>=min) && (i<=max) && ((i%2) == (j%2)))//(i%2) == (j%2) pour que le numéro de colonne soit pair quand j est paire et inversement -> n%2 retourne 0 si paire et 1 sinon  
                 System.out.print(j);  
             else  
                 System.out.print(" ");  
         }  
          System.out.println("");  
     }  
  } 
} 
0
domxaline
 
ok ça marche,merci beaucoup
0