【问题标题】:How can I split my user String and arrange them in column and rows given the Split Size?如何拆分我的用户字符串并在给定拆分大小的情况下将它们排列在列和行中?
【发布时间】:2020-03-09 13:59:07
【问题描述】:

我几乎完成了这项活动,我只需要根据用户的拆分大小将它们排列在列和行中,并且我被困在只打印字符串本身的输出中。这是我目前的代码。

    Scanner lagoScan = new Scanner(System.in);

    System.out.println("Enter String:");
    String letters = lagoScan.next();



    final int numInLetters = letters.length(); // converted string to number length

    System.out.println("Enter Split Size:");
    int splitSize = lagoScan.nextInt();




    if (numInLetters % splitSize == 0) {

    System.out.println("The Given String is: "+letters);
    System.out.println("The Split String are:");

    //My Split here

    String []in_array;

    in_array = letters.split(""); //Note this there is no delimiter 
    for(int k=0; k < in_array.length; k++){


       System.out.print(" "+in_array[k]);

    }


    // Split ENdss
    }

    else {
    System.out.println("Given input is not divisible by input size.");
    }

}

这是我试图遵循的输出

【问题讨论】:

  • 您只是想分成 3 人一组吗?
  • 不,例如,如果拆分大小为“5”,则字符串会将自身列成 5 列并将自身分组为行。这就是为什么我用用户声明整除,遗憾的是我被困住了,请帮忙。

标签: java arrays split


【解决方案1】:

这是一个可能的解决方案:

for (int i = 1; i <= inArray.length; i++) {
  // print the current char.
  System.out.print(inArray[i - 1]);

  // if it's over the split size then print a line break
  // for split size = 3
  // i = 1 - print the char, i = 2, print the char, i = 3, print the char + line break
  if (i % splitSize == 0) {
   System.out.println();
  }

}

【讨论】:

    猜你喜欢
    • 2017-05-23
    • 1970-01-01
    • 2021-10-18
    • 2020-04-09
    • 1970-01-01
    • 2011-07-14
    • 2019-12-07
    • 2011-06-20
    • 2018-01-03
    相关资源
    最近更新 更多