Reputation: 21
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?
Upvotes: 2
Views: 1001
Reputation: 39
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));
}
Upvotes: 1
Reputation: 31
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
Upvotes: 0
Reputation: 25932
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?
Upvotes: 2
Reputation: 393946
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));
}
Upvotes: 3