0
I have a basic college project and one of the requirements of the exercise is to remove the last value from an array of integers. I am not able to do with the last value be removed without using an Arraylist, another specification would be not using an Arraylist and using the Pop function for such action, would need a help, because the only method I found would be to replace the last value with 0 and copy that array to a new array, but I think it would not be the most efficient, follow the code with the other functions of the code:
public class Pilha {
Scanner in = new Scanner(System.in);
private int top;
private int[] element = new int[10];
Pilha(){
}
public int Push(){
System.out.println("Insira os numeros desejado");
for(int j = 10; j > 0; j-- ){
top = in.nextInt();
element[j-1] = top;
}
return top;
}
public int Pop(){
return 0;
}
public void Show(){
for(int i = 10; i > 0; i--){
System.out.println(element[i-1]);
}
}
public void Menu(){
System.out.println("Digite o que quer fazer");
System.out.println("Digite 1 para inserir na pilha");
System.out.println("Digite 2 para remover o ultimo elemento");
System.out.println("Digite 3 para mostrar a pilha");
}
public void Menu2(){
System.out.println("Digite o que quer fazer");
System.out.println("Digite 2 para mostrar a pilha");
System.out.println("Digite 3 para remover o ultimo elemento");
}
Hi Jose, I tried here and even copied and pasted your code but it gives an error in the Pop function and even tried to turn it into method but it still didn’t work.
– ChrisMM
What is the error shown? If it is element[Count] = new Integer(null);' I think there is no way to play a null value and you should use the same 0
– José Henrique Luckmann
It was in himself, and I’m doing this way "ugly" even to replace the last value by 0, but I need to make it gradually change and I’m with this problem now.
– ChrisMM
What do you mean by "gradually change"?
– José Henrique Luckmann
Remove one by one, gradually. Each time I call the function I move in the array and changed k-1 by 0.
– ChrisMM
After I edited the above code, is he no longer behaving this way? After all when he Zera the value he dimmed 1 of the counter
– José Henrique Luckmann
Sorry, I hadn’t seen that you had edited the code, I’ll test it.
– ChrisMM
I tested it, but says that there is an error that says that the Pop function has to return an int value and in this case it is treated as a method, with no return.
– ChrisMM
Take a look at my change, I changed it to not return any value
– José Henrique Luckmann
The
Pop
should not return void? There is also a problem if you fill the vector: when you give pop, the position that will be zeroed is 10, which goes beyond the last element of the vector (a vector of 10 houses goes from 0 to 9)– Jefferson Quesado
You’re right @Jeffersonquesado, it was an oversight on my part, I changed the code
– José Henrique Luckmann