我是Java的新手,我有一个任务是创建一个简单的Socket程序来查找数字的平均值。但是在尝试运行我的程序时遇到了错误。
我试图解决这个问题,但仍然没有任何线索...
我的服务器名为“server.java”,客户端名为“rerata.java”
但是当我尝试在客户端上输入数据rerata.java并使用字段“rerata 10 2 3”时,它会显示如下错误:
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;
}
答案 0 :(得分: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
处的元素。