2014-10-27 30 views
0

我想写一个java代码,它将输入的字符串和块大小作为输入,并将字符串转换为给定大小的块。请注意,最后一个块可能小于请求的大小。将输入字符串分块成每行字符数java编程

String? abcdefghijklmnopqrstuvwxyz 
Chunk size? 4 
abcd 
efgh 
ijkl 
mnop 
qrst 
uvwx 
yz 

我不知道这一点,我一直在做这个工作了一段时间,所以我在这里:继承人的输出会是什么样的例子。

这是我现在所拥有的代码,但很多已经搬来搬去只是尝试:

package Oct_27_2014; 

import java.util.Scanner; 

public class ChunkingAPhrase { 

public static void main(String[] args) { 
    // declare variables 
    int chunkNumber; 
    String phrase; 
    int start = 0; 

    // get input 
    Scanner scan = new Scanner(System.in); 

    System.out.print("String? "); 
    phrase = scan.nextLine(); 
    System.out.print("Chunk size? "); 
    chunkNumber = scan.nextInt(); 

    // parse string 

    while(start < phrase.length()) { 
     String chunks = phrase.substring(start, chunkNumber); 
     start++; 


     if (phrase.indexOf(chunkNumber) != start) { 
      System.out.println(chunks); 
      System.out.println(); 

     }else{ 

     } 
    } 
} 
} 

这是输出我得到这个代码:

String? abcdefg12345 
Chunk size? 3 
abc 
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1 

bc 

c 
at java.lang.String.substring(Unknown Source) 
at Oct_27_2014.ChunkingAPhrase.main(ChunkingAPhrase.java:24) 

回答

0

的问题在于substring方法要求您为要提取的块指定开始索引和结束索引,而不是开始索引和长度。所以你需要确定最终指数应该是什么。它可能是开始索引加上块的长度,或者当前块可能会一直到字符串的末尾。最后,下一次迭代的开始索引将是当前迭代的结束索引。

所以用这个替换你的while循环。我认为别的什么都不需要改变。祝你好运。

while (start < phrase.length()) { 
    int end = start + chunkNumber; 
    if (end > phrase.length()) { 
     end = phrase.length(); 
    } 

    System.out.println(phrase.substring(start, end)); 
    start = end; 
} 
+0

这工作完美,有道理。只是想说谢谢,我试图弄清楚这一点,我工作太久了! – Emily 2014-10-27 02:50:23

+0

非常欢迎,@Emily。祝您学习愉快。 – 2014-10-27 02:55:34

相关问题