数组越界并将list <Object>转换为字符串[]

时间:2019-11-26 04:44:18

标签: java arrays spring-boot

嗨,我正在尝试读取数组中的所有数据,并产生ArrayOutOfBoundsException,我想我需要对其进行递减,但不知道每个循环如何使用,有人可以帮助我在这里找到代码谢谢

@PostMapping(path = "/createBooking/{location}")
public ResponseEntity<String> create(@PathVariable(value = "location") String location,
        @Validated @RequestBody Booking book) {
    book.setStatus("reserved");
    book.setBookingCode(generatedString);

    bookingRepository.save(book);

    MimeMessage message = sender.createMimeMessage();
    MimeMessageHelper helper = new MimeMessageHelper(message);
    StringBuilder sb = new StringBuilder();

    try {
        String[] array = new String[book.getAtt().size()];
        int index = array.length - 1;
        for (Object value : book.getAtt()) {
            array[index--] = String.valueOf( value );
        }
        helper.setTo(array[index]);
        sb.append("Agenda:" + " " + book.getBookingDesc()).append(System.lineSeparator());
        sb.append("When:" +  " " + book.getDateBooked() + " " + book.getStartTime() + " " + "To" + " " + book.getEndTime())
                .append(System.lineSeparator());
        sb.append("Where:" + " " + location).append(System.lineSeparator());
        sb.append("By:" + " " + book.getBookedUser()).append(System.lineSeparator());
        sb.append("Booking code:" + " " + generatedString);
        helper.setText(sb.toString());
        helper.setSubject("Meeting");
    } catch (MessagingException e) {
        e.printStackTrace();
        return new ResponseEntity<>("Error while sending mail ..", HttpStatus.BAD_REQUEST);
    }
    sender.send(message);

    return new ResponseEntity<>("Inputs have been saved", HttpStatus.OK);
}

如果能告诉我我是否做得也很感谢,谢谢

编辑:这是跟踪错误 编辑:我添加了整个班级

"trace": "java.lang.ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 2\r\n\tat com.example.rba.controller.Controller.create(Controller.java:79)\r\n\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\r\n\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)\r\n\tat java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\r\n\tat java.base/java.lang.reflect.Method.invoke(Method.java:567)\r\n\tat org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190)\r\n\tat org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest

4 个答案:

答案 0 :(得分:3)

数组索引以o开头,因此array.length将导致ArrayOutOfBoundsException。您可以将索引初始化为0并按以下方式使用

   int index = 0;
    for (Object value : book.getAtt()) {
       array[index++] = String.valueOf( value );
    }

或者如果要从末尾插入

int index = array.length-1;
for (Object value : book.getAtt()) {
       array[index--] = String.valueOf( value );
}

如果您只想设置helper.setTo(array[index]);中列表的第一个元素 无需创建单独的数组,只需执行helper.setTo(book.getAtt().get(0))

答案 1 :(得分:1)

    You can do this 

String[] array = new String[book.getAtt().size()];
                int index = array.length-1;
                for (Object value : book.getAtt()) {
                    array[index] = String.valueOf( value );
                    index--;
                }

答案 2 :(得分:1)

例外将出现在:

import mysql from 'mysql';
var connection = mysql.createConnection({
    host: 'DB_host',
    user: 'DB_user',
    password: 'DB_password',
    database:'DB_name'
});

connection.connect(function(err) {
    if (err) {
        console.error('error connecting: ' + err.stack);
        return;
    }
    console.log('data base connected as id ' + connection.threadId);
});

connection.on('error', function(err) {
    console.log('db error normal;', err);
    if(err.code === 'PROTOCOL_CONNECTION_LOST') {
        console.log('connect lost');                        
    } 
    else {                                     
        throw err;                                 
    }
});

//keep active your database connection

setInterval(function () {
    console.log('timeout completed'); 
    var sql="select id from table_name limit 1";
    connection.query(sql, function(err, result, field){
        console.log('running query for non idle ');
    });
}, 600000); 

module.exports = {connection, mysql};

您的循环迭代将像这样工作: 第一次迭代:值存储在最后一个索引(n),然后索引= n-1 第二次迭代:将值存储在n-1个索引处,并且索引= n-2 .... 上次迭代:将值存储在0索引处,并且n变为-1。

现在,当您尝试将辅助程序设置为array [-1]时,它将为您提供ArrayIndexOutOfBound。

如果您认为这有帮助,请不要忘记将其标记为答案。

答案 3 :(得分:0)

问题解决了,我只是移动了helper.setTo(array [index]);在循环内部,错误消失了,但是有一个新错误,但是不同的主题谢谢您