Home > Blockchain >  Every two adjacent elements in this list forms an ordered pair in Java
Every two adjacent elements in this list forms an ordered pair in Java

Time:10-21

I have questions about this one Every two adjacent elements in this list forms an ordered pair

Input: 1 4 2 4 3 8

Output: RELATION: { (1,4), (2,4), (3,8) }

I use Scanner to read the line and after that I use :

List<String> rel = Arrays.asList(relation.split(" "));
String rel1 = String.join(", ", rel);
System.out.println("RELATION: " "{ " rel1 " }");

but the output just gave me: RELATION: { 1, 4, 2, 4, 3, 8 } not pair them in 2 like the output I wanted. Could someone help me with this please?

I also used this code but it gives me wrong pairs

(1,4
4,2
2,4):
for (int i=0;i<rel.size()/2;i  ){
System.out.println(rel.get(i) "," rel.get(i 1));}

CodePudding user response:

for (int i=0;i<rel.size()/2;i  ){
System.out.println(rel.get(i) "," rel.get(i 1));}

i only goes up by one each time, so of course it will emit (1, 4), (4, 2), ...

You probably want something like

for (int i=0;i<rel.size();i  = 2)

which increases i by two every time. Alternately, you could write rel.get(2 * i) and rel.get(2 * i 1), if you thought that was better.

CodePudding user response:

Below code will work according to your requirement -

String relation = "1 4 2 4 3 8";
List<String> rel = Arrays.asList(relation.split(" "));
for (int i=0;i<rel.size();i =2){
   System.out.println(rel.get(i) "," rel.get(i 1));
}
  • Related