服务器显示错误的数据

时间:2017-10-25 17:42:22

标签: java sockets server

我正在写一个客户端和服务器,问题是什么时候发送整数到服务器,我希望服务器显示它们我得到的其他数字比我发送的数字,请注意其他字符串工作正常< / p>

你知道为什么会这样吗?

非常感谢提前! 客户

   Socket socket = new Socket("localhost",3333);

    OutputStreamWriter Output= new OutputStreamWriter(socket.getOutputStream());
    PrintWriter sender= new PrintWriter(Output);
    //creating the hotel by sending to the server the number of rooms
    System.out.println("please enter the number of the rooms");
    String roomsOfTheHotel=scanner.nextLine();
    sender.println(roomsOfTheHotel);
    //providing the information that needed to create a person class
    System.out.println("Enter the first name");
    String fname= scanner.nextLine();
    sender.println(fname);

    System.out.println("Enter the last name");
    String lname= scanner.nextLine();
    sender.println(lname);

    System.out.println("Enter the age");
    String  age= scanner.nextLine();
    sender.println(age);

    System.out.println("Enter the number of days");
    String  numberOfDays= scanner.nextLine();
    sender.println(numberOfDays);

    System.out.println("Enter the roomNumber");
    String roomNumber= scanner.nextLine();
    sender.println(roomNumber);

    Output.flush();

服务器      ServerSocket serverSocket = new ServerSocket(3333);

    DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
    Date date = new Date();
    String todaysDate= dateFormat.format(date);

    System.out.println("System is waiting");

    Socket serverSideSocket= serverSocket.accept();


    InputStreamReader input=new  InputStreamReader(serverSideSocket.getInputStream());
    BufferedReader reader= new BufferedReader(input);
  int roomOfTheHotel= Integer.parseInt(String.valueOf(reader.read()));
    System.out.println(roomOfTheHotel);
    Hotel1 hotel = new Hotel1(roomOfTheHotel);

    String fname= reader.readLine();
    System.out.println(fname);

    String lname= reader.readLine();
    System.out.println(lname);

    int age = Integer.parseInt(String.valueOf(reader.read()));
    System.out.println(age);


    int numberOfDays = Integer.parseInt(String.valueOf(reader.read()));
    System.out.println(numberOfDays);

    int roomNumber = Integer.parseInt(String.valueOf(reader.read()));
    System.out.println(roomNumber);
  

实施例

输入 输入年龄

27

输入天数

4

输入roomNumber

3

输出

97

115

115

1 个答案:

答案 0 :(得分:0)

BufferedReader.read()返回单个字符(作为int)

要将其转换为正确的字母,请使用(char)reader.read(),然后将其放入字符串/读取到int - 当前如果读者读取“5”,it will give you the number value of it (53),则转换到String(“53”),并解析为int(53再次)

使用BufferedReader.readLine()(返回一个String)获取完整的输入行并相应地解析它可能更有用

int roomOfTheHotel= Integer.parseInt(String.valueOf(reader.read()));

应该是以下之一:

int roomOfTheHotel = Integer.parseInt(reader.readLine());

int roomOfTheHotel = Integer.parseInt("" + ((char)reader.read()));

int roomOfTheHotel = reader.read() - '0';