Note that there are some explanatory texts on larger screens.

plurals
  1. POJava - Stacks - checking if 2 numbers of the stack equal 100
    primarykey
    data
    text
    <p>I have to check the sum of which 2 values in the stack equal 100 and print out the indecis and the numbers. I have made this possible using arrays but i can't get it to work using stacks. Please help me. I have wrote the following until now and it doesn't give me the right output.</p> <pre><code>import java.util.Stack; public class 2 { public static void main(String[] args) { int x = 100; Stack stack=new Stack(); Stack tempStack=new Stack(); stack.push(new Integer(20)); stack.push(new Integer(53)); stack.push(new Integer(41)); stack.push(new Integer(38)); stack.push(new Integer(28)); stack.push(new Integer(47)); stack.push(new Integer(70)); stack.push(new Integer(30)); stack.push(new Integer(80)); stack.push(new Integer(400)); stack.push(new Integer(3)); stack.push(new Integer(20)); tempStack = (Stack) stack.clone(); for (int i=0; i&lt;stack.size(); i++) { tempStack = (Stack) stack.clone(); int value = (Integer) stack.pop(); if (!stack.isEmpty()) { for (int k=0; k&lt;tempStack.size(); k++) { int tmp = (Integer) tempStack.pop(); if ((value + tmp) == x) { System.out.println("Indices " + i + " &amp; " + k + " with values " + value + " &amp; " + tmp); } } } } } } </code></pre> <p>The following is my array based solution:</p> <pre><code>public class 1 { public static void main(String[] args) { int x = 100; int [] array = {20,3,400,80,30,70,20,47,28,38,41,53,20}; for (int i=0; i&lt;array.length; i++){ int temp1 = array[i]; for (int k=1; k&lt;array.length; k++) { int temp2 = array[k]; if ((temp1+temp2)==x) System.out.println("Indices " + i + " &amp; " + k + " with values " + temp1 + " &amp; " + temp2); } } } } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload