如何将int保存在堆栈中? (java初学者)

时间:2019-03-22 10:30:29

标签: java server stack client

我试图将服务器从客户端获取的int值保存到堆栈中,但不知道从哪里开始或做什么。

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);
    }
}

我希望将温度保存在堆栈中。

任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:0)

尝试下面的代码。

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);
    }
}

答案 1 :(得分:0)

我假设您的意思是要创建一个堆栈数据结构,即先进先出结构。

您需要声明一个stack对象并将temp变量压入其中。修改后的代码如下所示

  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());
      }
   }

但是,如果您指的是将变量“堆栈”保存为内存分配的行为,请看看this问题。

希望这会有所帮助!