子串不工作(循环)

时间:2017-10-25 19:43:00

标签: java for-loop syntax-error substring

我正在努力实现以下输出

A1 = 123然后在下一行A2 = 456并且A3 = 678

但是当我运行它时,它会循环并获得10次。我只需要这三条线,如A1,A2和A3。长度可以根据需求而变化。以下是我的代码。请提出解决方案。

public class SusbTesting {


    public static void main (String args[]){

          String text = "123456789"; //The text

          int len = text.length(); //Get the length
         // text = text.substring(0,4)+ "_"+ text.substring(4,6) + "-" + text.substring(6);
        System.out.println("testing test >>>" +text);
         for (int k = 0; k < text.length(); k++) 
         {
             String A1  =   text.substring(0,2);
             String A2  =   text.substring(3,6);
             String A3  =   text.substring(7,9);
             text = A1+ "_"+ A2 + "-" + A3;
             System.out.println("testing  >>>" +text);
         }


    }
}

2 个答案:

答案 0 :(得分:0)

尽量不要使用循环:

public class SusbTesting {
   public static void main(String [] args) {
      String text = "123456789";
      String a1 = text.substring(0, 3), a2 = text.substring(3, 6), a3 = 
      text.substring(6, 9);
      System.out.println(a1);
      System.out.println(a2);
      System.out.println(a3);
   }
}

答案 1 :(得分:0)

String text = "123456789"; //The text

        int len = text.length(); //Get the length

        String A1 = text.substring(0,3);
        String A2 = text.substring(3,6);
        String A3 = text.substring(6,9);
        System.out.println(A1);
        System.out.println(A2);
        System.out.println(A3);

试试这个。我不认为你需要一个循环。