0

i'm new to Java and i got a task to make a simple Socket program to find the Average of numbers. But i got an error when trying to run my program.

i've tried to solve this but still have no clue...

I have this Server called "server.java" and the Client called "rerata.java"

But When i try to input data on the Client which is rerata.java with field "rerata 10 2 3" it shows error like this :

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

So how to solve this please ?

This is my 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();

     }
    }
}

And this is my 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;
}

1 Answer 1

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

Should be

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

because arrays are 0 base indexed in Java. When you're doing

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

you're trying to access the element at index angka.length in the last iteration which doesn't exists.

enter image description here

Sign up to request clarification or add additional context in comments.

2 Comments

when server try to split the input from client like "rerata 10 2 3". i want the array that will be process are from the second array which is 10. so it'll be like from 10 2 3
Thanks, Resolved. i was never too careful when it came to solving problem like this. Once again, thank you so much. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.