-2

I am trying to save the value of an int that my server gets from the client to a stack but do not know where to begin or what to do.

public class ser {
    public static int number, temp;

    public static void main(String args[]) throws UnknownHostException, IOException 
    {
        ServerSocket s1=new ServerSocket(1342);
        Socket ss = s1.accept();
        Scanner sc = new Scanner (ss.getInputStream());
        number = sc.nextInt();

        temp = number*2;

        PrintStream p=new PrintStream(ss.getOutputStream());
        p.println(temp);
    }
}

I want the temp to be saved in a stack.

Any help will be appreciated.

khelwood
  • 55,782
  • 14
  • 81
  • 108
Hasso
  • 29
  • 5
  • You'll need a stack first. Then since the standard implementation will accept objects only you'd need to box the `int` with an `Integer` but the compiler might do that for you automatically. If you want a stack of primitives there probably is some library containing something like an `IntStack` out there. – Thomas Mar 22 '19 at 10:33
  • 2
    What is your question? You don't know how to declare variable? Which type to use for `Stack`? – talex Mar 22 '19 at 10:33

2 Answers2

0

try below code.

import java.io.*; 
import java.util.*; 

public class ser {
    public static int number, temp;

    public static void main(String args[]) throws UnknownHostException, IOException 
    {
        ServerSocket s1=new ServerSocket(1342);
        Socket ss = s1.accept();
        Scanner sc = new Scanner (ss.getInputStream());
        number = sc.nextInt();

        temp = number*2;

        Stack<Integer> stack = new Stack<Integer>(); 
        stack.push(number);
        stack.push(temp);

        PrintStream p=new PrintStream(ss.getOutputStream());
        p.println(temp);
    }
}
Onkar Musale
  • 909
  • 10
  • 25
0

I assume you mean you want to create a stack data structure, i.e. a first in last out structure.

You need to declare a stack object and push your temp variable in it. The modified code would look something like this

  import java.io.*; 
  import java.util.*; 

  public class ser {
      public static int number, temp;

      public static void main(String args[]) throws UnknownHostException, 
  IOException 
      {
          ServerSocket s1=new ServerSocket(1342);
          Socket ss = s1.accept();
          Scanner sc = new Scanner (ss.getInputStream());
          number = sc.nextInt();

          temp = number*2;

          Stack<Integer> stack = new Stack<Integer>(); 
          stack.push(temp);

          PrintStream p=new PrintStream(ss.getOutputStream());
          // this should print your temp number, now part of the stack
          p.println(stack.peek());
      }
   }

However, if you are referring to the act of saving variables "on stack" as the memory allocation are, do take a look at this question.

Hope this helps!