简体   繁体   English

如何一次打印一个单词两个字母? - java

[英]How can I print a word two letters at a time? - java

The input is supposed to have an even length.输入应该有一个偶数长度。 The problem is that on the first iteration of the loop, it print Sc, but then it prints ch instead of ho.问题是在循环的第一次迭代中,它打印出 Sc,但随后打印出 ch 而不是 ho。 I'm not sure how to make that jump.我不知道怎么跳。

public static void twoAtATime(String a) { // School
        int len = a.length();
        if(len%2 == 0) {
            for(int i = 0; i <a.length()/2; i++) {
                    System.out.print(a.substring(i,i+1) + a.substring(i+1,i+2));
                    System.out.println();
            }
        }

The output is supposed to be like this: output 应该是这样的:

Sc
ho
ol

To fix it:要解决这个问题:

  1. Increase i by 2 .i增加2
  2. Iterate until i < len .迭代直到i < len

You can improve it:你可以改进它:

  1. By calling substring once for two chars.通过为两个字符调用一次substring
  2. Using println with param.使用带有参数的println
  3. Incrementing i once - i += 2 .增加i一次 - i += 2

After improvements:改进后:

public static void twoAtATime(String s) {
    int len = s.length();
    if (len % 2 == 0) {
        for (int i = 0; i < len; ) {
            System.out.println(s.substring(i, i += 2));
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何检查两个字符串是否具有相同的字母,但只打印一次常见的字母? - How can I check if two strings have the same letters, but only print the common letters once? 我怎样才能打乱一个单词的字母? - How can I shuffle the letters of a word? Java-如何在BubbleSorting之后将值作为单词打印出来? - Java - How can I print out a value as a word after BubbleSorting? 如何按照与 Java 7 兼容的出现顺序对单词的字母进行排序? - How can I sort the letters of a word according to the order of occurrences compatible with Java 7? 如何使用 Java Swing 在两列中打印文本? - How can I print a text in two columns using Java Swing? 如何使单词中的字母显示为“ Hangman”游戏的下划线? - How can I make letters in a word appear as underscores for a Hangman game? 如果一个单词的字母数均匀,则每行打印两个字母吗? - if a word has an even amount of letters print the word with two letters per line? 如何使用Java中的for循环以三角形形式打印出单词chicken? - how can I use the for loop in java to print out the word chicken in a triangle shape? 如何从按字母顺序排序的不同行上的输入中打印每个不同的单词? - Java - How can I print every different word from an input on a different line sorted in an alphabetical order? - Java 如何使用 bufferedreader 和 treemap 打印文本中最常见的单词? - Java - How can I print the most frequent word in a text using bufferedreader and treemap ? - Java
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM