2
import java.util.Scanner;

public class TwoAtATime {

  public static void main(String[] args) {
    Scanner scan= new Scanner(System.in);
    System.out.println("Enter a word with an even amount of letters:");
    String w = scan.nextLine();
    if(w.length() % 2 == 0) {
      for(int i= 0; i<w.length(); i++) {
        System.out.println(w.charAt(i));
      }
    } else {
      System.out.println("You didnt follow directions");
    }
  }
}

This is my code so far and I can't figure out how to make it print two per line instead of one, any help?

Mateusz Dymczyk
  • 14,969
  • 10
  • 59
  • 94

4 Answers4

3

Here's one way to do it :

if (w.length() % 2 == 0) {
    for(int i = 0; i < w.length(); i+=2) {
        System.out.print(w.charAt(i));
        System.out.println(w.charAt(i+1));
    }
}

Or you could do it with String::substring.

if (w.length() % 2 == 0) {
    for(int i = 0; i < w.length(); i+=2)
        System.out.println(w.substring(i,i+2));
}
Eran
  • 387,369
  • 54
  • 702
  • 768
2

Slight modification to @Eran's answer, you don't need to divide w.length() by 2. Also, adding the char's does not concatenate them.

String w = "12345678";
if (w.length() % 2 == 0) {
    for(int i= 0; i<w.length(); i+=2)
        System.out.println(""+w.charAt(i)+w.charAt(i+1));
}

Gives:

12
34
56
78

Reference: In Java, is the result of the addition of two chars an int or a char?

Community
  • 1
  • 1
Nick Grealy
  • 24,216
  • 9
  • 104
  • 119
1

Just change the "for" loop to this:

 for(int i= 1; i<w.length(); i+=2){
     System.out.println(w.charAt(i-1) +""+ w.charAt(i));
 }
Uhha
  • 29
  • 3
0

you can use Google Guava which split your string by fixed length (2 in your case).

for(String subStr : Splitter.fixedLength(2).split(w)){
    System.out.println(subStr);
}

here is the java doc for Splitter

Yang Zhang
  • 31
  • 2