java - 我想运行我的代码,但终端告诉索引超出范围。可能是因为 ArrayList methode 得到 ot smth 这样
问题描述
我正在尝试运行我的代码。但终端告诉:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 1, Size: 1
at java.util.ArrayList.rangeCheck(Unknown Source)
at java.util.ArrayList.get(Unknown Source)
at CF455A.main(CF455A.java:25)
第 25 个字符串是: game.remove(game.get(max+1));
我的代码:
import java.util.*;
import java.lang.*;
import java.io.*;
public class CF455A {
public static void main(String args[]) throws java.lang.Exception {
Scanner in = new Scanner (System.in);
int n = in.nextInt();
int max = 0;
ArrayList<Integer> game = new ArrayList<Integer>();
for(int i = 0; i < n; i++){
int t = in.nextInt();
game.add(i, t);
}
int counter = 0;
while(game.size()>0){
for(int j = 0; j < game.size(); j++){
if(max <= (int)game.get(j)){max=j;}
for(int i = 0; i < game.size(); i++){
counter = counter + (int)game.get(max);
game.remove(game.get(max));
game.remove(game.get(max+1));
game.remove(game.get(max-1));
}
}
}
System.out.print(counter);
in.close();
}
我认为这是因为 ArrayList 或类似game.get();
or的方法game.remove();
。我只是想更改 ArrayList 的元素之一的值
项目清单
解决方案
根据逻辑:-如果我将输入输入为:- 5 1 2 3 4 5 然后首先通过:- game.size() = 5; while 条件为 true -> 并尝试删除索引 (1,0,-1) 处的项目。因此 (-1) IndexOutOfBounds失败。请按如下方式进行空值检查:-
import java.util.*;
import java.lang.*;
import java.io.*;
public class TestMemberOuter1 {
public static void main(String args[]) throws java.lang.Exception {
Scanner in = new Scanner (System.in);
int n = in.nextInt();
int max = 0;
ArrayList<Integer> game = new ArrayList<Integer>();
for(int i = 0; i < n; i++){
int t = in.nextInt();
game.add(i, t);
}
int counter = 0;
while(game.size()>0){
for(int j = 0; j < game.size(); j++){
if(max <= (int)game.get(j))
{
max=j;
}
for(int i = 0; i < game.size(); i++){
counter = counter + (int)game.get(max);
if(max < game.size() )
{
game.remove(game.get(max));
}
if(max+1 < game.size() )
{
game.remove(game.get(max+1));
}
if(max-1 > 0 )
{
game.remove(game.get(max-1));
}
}
}
}
System.out.print(counter);
in.close();
}
}
推荐阅读
- css - CSS通配符悬停在codepen上但不在本地或服务器上
- c - 如何制作包含我的标题的 Makefile?
- javascript - 对象在接口中属于“未知”类型
- sql - 计算每行的第一个和第二个最大值以及两个雪花 SQL 的平均值
- c++ - c ++编译器错误“X”没有命名类型,但我有包含
- python - 将 pyspark 数据框中的子字段分组到新数据框中并按链接列排序
- c# - Nswag - 指定控制器名称的顺序
- php - PHP多维数组 - 获取最后一个索引中元素的值?
- javascript - 来自 JS 的 PHP 解密在更长的值上中断
- python - 使用比较器运算符作为用户输入