英文:
Edit arraylist with the number not the index
问题
如何通过值而不是索引号来编辑ArrayList?使用arraylist.set(93, 92) 方法。
ArrayList al = new ArrayList();
Random rand = new Random();
Scanner sc = new Scanner(System.in);
// 用随机整数(1到100之间)生成大小为10的ArrayList
for (int j = 0; j < 10; j++) {
pick = rand.nextInt(100);
al.add(pick);
}
System.out.println("请输入要更新或编辑的整数:");
int toUpdateInt = sc.nextInt();
System.out.println("请输入新数据的值:");
int newValue = sc.nextInt();
al.set(toUpdateInt, newValue);
System.out.println(al);
在我的代码中,它要求输入索引号(toUpdateInt)进行设置。我想使用随机数来设置索引号。如何实现?
英文:
How to edit the arraylist using the value and not the index number? with the use of arraylist.set( 93, 92)
ArrayList al = new ArrayList();
Random rand = new Random();
Scanner sc = new Scanner(System.in);
//Generates arraylsit with size 10 with random integers from 1 to 100
for (int j = 0; j<10; j++)
{
pick = rand.nextInt(100);
al.add(pick);
}
System.out.println("Please enter an integer to update or edit: ");
int toUpdateInt = sc.nextInt();
System.out.println("Please eneter the new value of data: ");
int newValue = sc.nextInt();
al.set(toUpdateInt, newValue);
System.out.println(al);
In my code it asks for the index number in the (toUpdateInt) I want to use the random number to set. How to?
答案1
得分: 1
对于一个Set
(无重复项,无顺序),这将是快速且简单的。
Set<Integer> al = new HashSet<>();
Random rand = new Random();
for (int j = 0; j < 10; j++) {
int pick = rand.nextInt(100);
al.add(pick);
}
...
al.remove(toUpdateInt);
al.add(newValue);
对于一个List
:
List<Integer> al = new ArrayList<>();
int index = al.indexOf(toUpdateInt);
if (index != -1) {
al.set(index, newValue);
}
英文:
For a Set
(no duplicates, no order) it would be fast and easy.
Set<Integer> al = new HashSet<>();
Random rand = new Random();
for (int j = 0; j < 10; j++)
{
int pick = rand.nextInt(100);
al.add(pick);
}
...
al.remove(toUpdateInt);
al.add(newValue);
For a List
:
List<Integer> al = new ArrayList<>();
int index = al.indexOf(toUpdateInt);
if (index != -1) {
al.set(index, newValue);
}
答案2
得分: 0
你还可以使用ArrayList.contains()方法,但这样也可以。
if (a1.indexOf(toUpdateInt) != -1) {
a1.set(a1.indexOf(toUpdateInt), newValue);
} else {
a1.add(newValue);
System.out.println("需要更新的整数不存在,因此已添加。");
}
英文:
You can also use Arraylist.contains() method, but this would be fine.
if(a1.indexOf(toUpdateInt) != -1) {
a1.set(a1.indexOf(toUpdateInt), newValue);
} else {
a1.add(newValue);
System.out.println("The integer to update is not available, and hence added it.");
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论