0

私はJavaが初めてで、単純なSocketプログラムを作成して数値の平均を見つけるタスクを取得しました。しかし、プログラムを実行しようとするとエラーが発生しました。

私はこれを解決しようとしましたが、まだ手がかりがありません...

「server.java」と呼ばれるこのサーバーと「rerata.java」と呼ばれるクライアントがあります

しかし、「rerata 10 2 3」フィールドを持つ rerata.java であるクライアントにデータを入力しようとすると、次のようなエラーが表示されます。

Exception in thread "Thread-0" java.lang.ArrayIndexOutOfBoundsException: 4 at rerata.server.run(server.java:45)

では、これを解決する方法を教えてください。

これは私のserver.javaです:

package rerata;

import java.net.*;
import java.io.*;
/**
 *
 * @author GT-13
 */
public class server extends Thread{

private static int port;
private ServerSocket serverSocket;

public server(int port) throws IOException
{
    serverSocket = new ServerSocket(port);
}
@Override
public void run()
{
    while(true)
    {
        try
        {
            System.out.println(" Wait Client : !!!!");
            Socket serper = serverSocket.accept();

            DataOutputStream acc = new DataOutputStream(serper.getOutputStream());
            acc.writeUTF("OK ");

            DataInputStream arr = new DataInputStream(serper.getInputStream());

            String kata = arr.readUTF();
            String[] angka = kata.split(" ");
            float hasil = 0;
            for(int i = 1; i <= angka.length;i++)
            {
                float nilai = 0;
                nilai = Float.parseFloat(angka[i]);
                hasil += nilai;
                System.out.println(hasil);
            }
            System.out.println(hasil);
            float kirim = (hasil/(angka.length-1));
            System.out.println(kirim);
            DataOutputStream  send = new DataOutputStream(serper.getOutputStream());
            send.writeFloat(kirim);
        }
          catch (SocketTimeoutException s) {
            System.out.println("Socket timed out!");
            break;
        } catch (IOException e) {
            e.printStackTrace();
            break;
        }
    }
}
public static void main(String[] args)
{
    port = 9000;
    try
    {
        System.out.println("Server Start....");
        Thread t = new server(port);
        t.start();
    }
    catch(IOException e) 
    {
        e.printStackTrace();

     }
    }
}

そして、これは私のrerata.javaです:

package rerata;

import java.io.*;
import java.net.Socket;

public class Rerata extends javax.swing.JFrame {

/**
 * Creates new form Rerata
 */
public Rerata() {
    initComponents();
}

/**
 * This method is called from within the constructor to initialize the form.
 * WARNING: Do NOT modify this code. The content of this method is always
 * regenerated by the Form Editor.
 */
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">                          
private void initComponents() {

    jLabel1 = new javax.swing.JLabel();
    nilai = new javax.swing.JTextField();
    excute = new javax.swing.JButton();
    jLabel2 = new javax.swing.JLabel();
    hasil = new javax.swing.JTextField();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    jLabel1.setText("N i l a i :");

    excute.setText("Excute");
    excute.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            excuteActionPerformed(evt);
        }
    });

    jLabel2.setText("H a s i l :");

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(13, 13, 13)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                        .addComponent(excute)
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(jLabel1)
                            .addGap(18, 18, 18)
                            .addComponent(nilai, javax.swing.GroupLayout.PREFERRED_SIZE, 253, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(jLabel2)
                    .addGap(18, 18, 18)
                    .addComponent(hasil, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE)))
            .addContainerGap(78, Short.MAX_VALUE))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGap(20, 20, 20)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(jLabel1)
                .addComponent(nilai, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGap(28, 28, 28)
            .addComponent(excute)
            .addGap(18, 18, 18)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(jLabel2)
                .addComponent(hasil, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addContainerGap(171, Short.MAX_VALUE))
    );

    pack();
}// </editor-fold>                        

private void excuteActionPerformed(java.awt.event.ActionEvent evt) {                                       
    // TODO add your handling code here:
    String sName = "localhost";
    int port = 9000;
    String angka;

    try {
        System.out.println("Client Start>>>>>"+"\n##########");
        System.out.println("Connecting to Server....\n##########");
        Socket client = new Socket(sName, port);

        OutputStream outToServer = client.getOutputStream();

        InputStream inFromServer1 = client.getInputStream();
        DataInputStream inOk = new DataInputStream(inFromServer1);
        System.out.println("Server : " + inOk.readUTF()+"\n##########");

        //System.out.println("Angka Pertama : ");
        angka = nilai.getText().trim();
        DataOutputStream outAngka1 = new DataOutputStream(outToServer);
        outAngka1.writeUTF(angka);

        InputStream inFromServer2 = client.getInputStream();
        DataInputStream inHasil = new DataInputStream(inFromServer2);
        String a = String.valueOf(inHasil.readFloat());
        hasil.setText(a);
        System.out.println(a);


        client.close();

    } catch (IOException e) {


    }
}                                      

/**
 * @param args the command line arguments
 */
public static void main(String args[]) {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(Rerata.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(Rerata.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(Rerata.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(Rerata.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new Rerata().setVisible(true);
        }
    });
}



 // Variables declaration - do not modify                     
    private javax.swing.JButton excute;
    private javax.swing.JTextField hasil;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JTextField nilai;
}
4

1 に答える 1

2
for(int i = 1; i <= angka.length;i++)

する必要があります

for(int i = 1; i < angka.length;i++)

配列は Java でインデックス付けされた 0 ベースであるためです。やってるとき

nilai = Float.parseFloat(angka[i]);

angka.length存在しない最後の反復で index の要素にアクセスしようとしています。

ここに画像の説明を入力

于 2013-11-15T09:04:36.333 に答える