我正在尝试将元素编号从一个数组复制到Java中另一个数组的输出

时间:2018-06-30 02:04:35

标签: java arrays

每当我打印输出时,它就会输出为0

 for (k=0;k < records.length - 1; k++) { // stores number in new array
        if ( records[k] == maxWins) {
            for (i=0; i < winners.length - 1; i++) {
                    winners[i] = k;
            }
        }
    } // end of storing 

我已经声明并初始化了适当的变量。如果您需要更多信息,我们将很乐意提供。

2 个答案:

答案 0 :(得分:0)

更改为以下代码应该对您有用:

int i = 0;
 for (k=0;k < records.length; k++) { 
        if ( records[k] == maxWins) { 
                  winners[i] = k; // you want to store one winner one time only, 
                                  // so dont use another loop inside this loop
                  i++;
        }
    } 

屏幕截图:

enter image description here enter image description here

  

代码改进:

     

不要将数组用于获奖者,因为   不同的时间点。而是使用列表并将其转换为   完成添加值后的数组。

答案 1 :(得分:0)

假设您要在源数组中收集与function getAllDevices(cb) { let rst; let query = Arduino.where({}); query.find((err, results) => { if (err) cb('[ERR] Erro buscando todos os dispositivos do banco para WEB.'); cb(null, results); }) } let updateDevicesStatus = () => { getAllConnectedClients() getAllDevices((err, devicesDB) => { if(err) // do something with the error devicesDB.forEach((currentDevice) => { connectedClients.forEach((currentClient) => { if (arduinoNM.connected[currentClient].clientID == currentDevice.clientID) { devicesOnline.push(currentDevice); } else { devicesOffline.push(currentDevice); } }); }); } 具有相同值的索引,可以这样解决

maxWins

为此,您可以使用诸如List<Integer> winnerList = new ArrayList<>(); for (int k = 0; k < records.length; k++) { // stores number in new array if (records[k] == maxWins) { winnerList.add(k); } } 之类的动态数据结构,而不是使用数组。使用数组会导致很多尾随零,并且会适得其反,因为我们不知道它的大小是否提前。您可以轻松地将数组最后转换为List

List