在java中用不同的组分隔列表元素
假设我有一个列表,它总是有偶数的计数。现在我想用不同的组索引分隔列表,条件如下在java中用不同的组分隔列表元素,java,list,arraylist,Java,List,Arraylist,假设我有一个列表,它总是有偶数的计数。现在我想用不同的组索引分隔列表,条件如下 1) First element (1st element) with one index (EX: 1) 2) Next two elements with same index (Ex: 2nd, 3rd element with index 2, 4th and 5th element with index 3) 3) Last
1) First element (1st element) with one index (EX: 1)
2) Next two elements with same index (Ex: 2nd, 3rd element with index 2,
4th and 5th element with index 3)
3) Last element(6th element) with index 4
我尝试使用嵌套for循环来实现同样的效果,但没有得到预期的输出
感谢您的帮助。
样本输入:
[2,3,53,52,33,12,44,66]
样本输出:
2 - 1
3 - 2
53 - 2
52 - 3
33 - 3
12 - 4
44 - 4
66 - 5
如果我正确理解了你的问题,这应该是正确的:
System.out.println(elements.get(0) + " - 1"); // Prints the first number, which has the value of 1
int value = 2; // Value corresponding to the number
for (int i = 1; i < elements.size(); i++) { // Loops through the list starting at second element (index of 1)
System.out.println(elements.get(i) + " - " + value); // Prints the number and the value
if (i % 2 == 0) value++; // Increases the value every two loops
}
System.out.println(elements.get(0)+“-1”);//打印第一个值为1的数字
int值=2;//与数字对应的值
for(int i=1;i
它首先打印出第一个数字和1,正如您所描述的,它们总是相互对应。然后它循环遍历从第二个数字(i=1)开始的数字列表,并打印出每个数字和相应的值。该值每两个循环增加一次,即每次循环数可被2整除时(i%2)。我已经使用两个附加变量z和count实现了这一点,我是 仅当计数%2为0时才递增z,最后我们需要检查 对于第三种情况,size-1等于i变量。 另外,对于第一个条件,当I计数器值为0时,我打印第一个索引处的arraylist值和I处的z变量值 请参阅下面的代码,我已经模拟了你的输入列表,我 已手动添加!请使用链接测试:
导入javafx.collections.ArrayChangeListener;
导入java.util.ArrayList;
导入java.util.Scanner;
公共班机{
公共静态void main(字符串[]args){
ArrayList a=新的ArrayList();
a、 增加(2);
a、 增加(3);
a、 增加(53);
a、 增加(52);
a、 增加(33);
a、 增加(12);
a、 增加(44);
a、 增加(66);
int i=0;
int z=2;
//计数通过检查中间数相对于mod 2的值来对中间数进行分组
整数计数=0;
对于(i=0;i0&&i!=(a.size()-1))
{
//如果计数为偶数,则增加z,以便打印两次组
如果(计数%2==0)
{
z++;
}
System.out.println(“+a.get(i)++++++++++z+”);
计数++;
}
如果(i==a.size()-1)
{
z++;
System.out.println(“+a.get(i)++++++++++z+”);
}
}
}
}
拥有代码这一事实是一个起点。在这里发布你的方法,这样我们就可以看到你有什么以及哪里出错了。听起来你好像在尝试对列表中的元素进行分类。如果列表元素总是唯一的,那么可以使用字典,其中列表元素是键,字典值是组/类别numbers@Vinod-我已经添加了答案,但不知道为什么对工作代码投反对票,请检查!
import javafx.collections.ArrayChangeListener;
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
ArrayList<Integer> a= new ArrayList<Integer>();
a.add(2);
a.add(3);
a.add(53);
a.add(52);
a.add(33);
a.add(12);
a.add(44);
a.add(66);
int i = 0;
int z = 2;
//Count to group the middle number by checking its value with respect to mod 2
int count = 0;
for(i = 0; i < a.size(); i++)
{
if(i == 0 )
{
z = i+1;
System.out.println(""+a.get(i)+" " + "" +z+"" );
}
if(i > 0 && i != (a.size() -1))
{
//Increament z if the count is even so that we print the group for two times
if(count%2 == 0)
{
z++;
}
System.out.println(""+a.get(i)+"" +" "+ ""+z+"" );
count ++;
}
if(i == a.size() -1 )
{
z++;
System.out.println(""+a.get(i)+"" +" "+ ""+z+"" );
}
}
}
}