NumberFormatException解析为加倍

时间:2016-02-11 16:51:58

标签: java datagram

当我从客户端向服务器发送值时,我得到如下例外情况。服务器dString = new Date().toString();中的语句正在执行而不是处理数据报包。有些人可以提供您的输入以更正服务器或我的客户端以获得准确的输出。

Exception in thread "Thread-2" java.lang.NumberFormatException: For input string: "45.0Feb 11 03:35:27 CST 2016"
    at sun.misc.FloatingDecimal.readJavaFormatString(Unknown Source)
    at java.lang.Double.parseDouble(Unknown Source)
    at com.loan.emi.QuoteServerThread.run(QuoteServerThread.java:75)
    at java.lang.Thread.run(Unknown Source)

.//服务器类

public class QuoteServerThread extends JFrame implements Runnable {

    protected DatagramSocket socket = null;
    protected BufferedReader in = null;
    protected boolean moreQuotes = true;
    private JTextArea jta = new JTextArea();

    public QuoteServerThread() throws IOException {
        this("QuoteServerThread");
    }

    public QuoteServerThread(String name) throws IOException {
        super(name);
        socket = new DatagramSocket(8300);
        add(new JScrollPane(jta), BorderLayout.CENTER);
        setVisible(true);
        setSize(400, 400);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setTitle("Server");// It is necessary to show the frame here
        try {
            in = new BufferedReader(new FileReader("one-liners.txt"));
        } catch (FileNotFoundException e) {
            jta.append("Couldn't open quote file. Serving time instead.");
        }
    }

    public void run() {
        while (moreQuotes) {
            try {
                byte[] buf = new byte[256];
                // Receive request for processing
                DatagramPacket packet
                        = new DatagramPacket(buf, buf.length);
                socket.receive(packet);
                // Figure out response
                String dString = null;
                if (in == null) {
                    dString = new Date().toString();
                } else {
                    dString = getNextQuote();
                }
                buf = dString.getBytes();
                // Send the response to the client
                //  at "address" and "port"
                InetAddress address = packet.getAddress();
                int port = packet.getPort();
                packet = new DatagramPacket(
                        buf, buf.length, address, port);
                socket.receive(packet);
                double rate = Double.parseDouble(new String(buf).trim());
                socket.send(packet);

                socket.receive(packet);
                double years = Double.parseDouble(new String(buf).trim());
                socket.send(packet);
                socket.receive(packet);
                double loan = Double.parseDouble(new String(buf).trim());
                socket.send(packet);
                double monthlyPayment = loan * (rate / 1200) / 
                        (1 - (Math.pow(1 / (1 + (rate / 1200)), years * 12)));
                socket.send(packet);
                double totalPayment = monthlyPayment * years * 12;
                socket.send(packet);
                jta.append("Interest Rate is " + rate + '\n');
                jta.append("Number Of years " + years + '\n');
                jta.append("Loan Amount is " + loan + '\n');
                jta.append("Monthly payment " + monthlyPayment + '\n');
                jta.append("Total Payment " + totalPayment + '\n');

            } catch (IOException e) {
                e.printStackTrace();
                moreQuotes = false;
            }
        }
        socket.close();
    }

    protected String getNextQuote() {
        String returnValue = null;
        try {
            if ((returnValue = in.readLine()) == null) {
                in.close();
                moreQuotes = false;
                returnValue = "No more quotes. Goodbye.";
            }
        } catch (IOException e) {
            returnValue = "IOException occurred in server.";
        }
        return returnValue;
    }
}

。 // 客户端类

public class DgClient extends JFrame {
    // Text field for receiving radius
    private JTextField jtf = new JTextField();
    JTextField interestRate = new JTextField();
    JTextField numberOfYears = new JTextField();
    JTextField loanAmount = new JTextField();
    JButton submit = new JButton("Submit");
    // Text area to display contents
    private JTextArea jta = new JTextArea();
    // Datagram socket
    private DatagramSocket socket;
    // The byte array for sending and receiving datagram packets
    private byte[] buf = new byte[256];
    // Server InetAddress
    private InetAddress address;
    // The packet sent to the server
    private DatagramPacket sendPacket;
    // The packet received from the server
    private DatagramPacket receivePacket;

    public static void main(String[] args) {
        new DgClient();
    }

    public DgClient() {
        // Panel p to hold the label and text field
        JPanel fieldsPanel = new JPanel();
        fieldsPanel.setLayout(new GridLayout(3, 3));
        fieldsPanel.add(new JLabel("Anual Interest Rate"));
        fieldsPanel.add(interestRate);
        fieldsPanel.add(new JLabel("Number Of Years"));
        fieldsPanel.add(numberOfYears);
        fieldsPanel.add(new JLabel("Loan Amount"));
        fieldsPanel.add(loanAmount);
        JPanel topPanel = new JPanel();
        topPanel.setLayout(new FlowLayout());
        topPanel.add(fieldsPanel);
        topPanel.add(submit);
        add(topPanel, BorderLayout.NORTH);
        add(new JScrollPane(jta), BorderLayout.CENTER);
        submit.addActionListener(new ButtonListener());
        setTitle("Loans Client");
        setVisible(true);
        setSize(400, 400);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true); // It is necessary to show the frame here!
        try {
            // get a datagram socket
            socket = new DatagramSocket();
            address = InetAddress.getByName("localhost");
            sendPacket
                    = new DatagramPacket(buf, buf.length, address, 8300);
            receivePacket = new DatagramPacket(buf, buf.length);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    private class ButtonListener implements ActionListener {

        public void actionPerformed(ActionEvent e) {
            try {
                // Initialize buffer for each iteration
                Arrays.fill(buf, (byte) 0);
                double rate = Double.parseDouble(interestRate.getText().trim());
                double years = Double.parseDouble(numberOfYears.getText().trim());
                double amount = Double.parseDouble(loanAmount.getText().trim());
                sendPacket.setData(new Double(rate).toString().getBytes());
                socket.send(sendPacket);
                sendPacket.setData(new Double(years).toString().getBytes());
                socket.send(sendPacket);
                sendPacket.setData(new Double(amount).toString().getBytes());
                socket.send(sendPacket);
                socket.receive(receivePacket);
                double monthlyRepayment = Double.parseDouble(new String(buf).trim());
                socket.receive(receivePacket);
                double totalAmount = Double.parseDouble(new String(buf).trim());
                jta.append("Interest Rate = " + rate + '\n');
                jta.append("Number of years = " + years + '\n');
                jta.append("Loan Amount = " + amount + '\n');
                jta.append("Monthly Repayment = " + monthlyRepayment + '\n');
                jta.append("Total Amount = " + totalAmount + '\n');
                socket.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
}

有人可以帮我解决导致错误的原因。我猜它是从客户端向服务器发送空值。但我不知道它的原因。

1 个答案:

答案 0 :(得分:0)

您未正确提取DatagramPacket中的数据。而不是new String(buf)你应该使用

new String(packet.getData(), packet.getOffset(), packet.getLength())

到处发生。

  

我猜它正在发送空值

这里没有空值。