Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/visual-studio-2008/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 以编程方式将文本输出置于for循环的中心_Java - Fatal编程技术网

Java 以编程方式将文本输出置于for循环的中心

Java 以编程方式将文本输出置于for循环的中心,java,Java,我试图推出以下字符模式: x xxx xxxxx xxxxxxx xxxxxxxxx 这就是我目前拥有的: String y = ""; for(int i = 0; i < 10; i++) { y=""; for(int s = 0; s < i; s++) { y+= "x"; } System.out.println(y); } 这是一种方法。我很清楚,目标模式每次执行循环都

我试图推出以下字符模式:

    x
   xxx
  xxxxx
 xxxxxxx
xxxxxxxxx
这就是我目前拥有的:

String y = "";
for(int i = 0; i < 10; i++)
{
      y="";
      for(int s = 0; s < i; s++)
      {
         y+= "x";
      }
      System.out.println(y);
}
这是一种方法。我很清楚,目标模式每次执行循环都会增加两个
x
,我知道我必须使用空格并插入它们。然而,我被这个非常简单的任务困住了


编辑:任务是只使用两个循环。不过,我想到了一种使用三个循环的方法,但无法直接找到一种使用两个循环的方法。

您可以解决您的问题,只需使用一个循环,就可以使用
padLeft
String.format
,下面是一个简单的示例:

public static void main(String args[]) {
    int n = 5;
    String str;
    for (int i = n; i > 0; i--) {
        str = String.format("%0" + ((n - i) * 2 + 1) + "d", 0).replace("0", "x");
        System.out.println(String.format("%1$" + ((i - 1 + str.length())) + "s", str));
    }
}
int baseWidth = 9;


for (int a = baseWidth ; a > 0 ; a--) {
  for (int b = 0 ; b < baseWidth - (a - 1) ; b++) {
    if (b < a - 1) {
      System.out.print(" ");
    }

    if (b >= a - 1 && b < baseWidth - (a - 1)) {
        System.out.print("X");
    }
  }

  System.out.print("\n");
}
输出

    x
   xxx
  xxxxx
 xxxxxxx
xxxxxxxxx

由于这个问题有许多不同的可能答案,这只是一个可能的解决方案

对于这个解决方案,我不需要在X之后打印空格。我只打印以前的

int baseWidth = 10;


for (int a = baseWidth ; a > 0 ; a--) {
  for (int b = 0 ; b < a - 1 ; b++) {
    System.out.print(" ");
  }

  for (int b = a - 1 ; b < baseWidth - (a - 1) ; b++) {
    System.out.print("X");
  }

  System.out.print("\n");
}
对于baseWidth=9,上述代码的结果如下:

    X
   XXX
  XXXXX
 XXXXXXX
XXXXXXXXX

编辑完文章后,下一个代码剪报执行与上一个相同的功能,但只有两个循环

int baseWidth = 9;


for (int a = baseWidth ; a > 0 ; a--) {
  for (int b = 0 ; b < baseWidth - (a - 1) ; b++) {
    if (b < a - 1) {
      System.out.print(" ");
    }

    if (b >= a - 1 && b < baseWidth - (a - 1)) {
        System.out.print("X");
    }
  }

  System.out.print("\n");
}
int baseWidth=9;
对于(int a=baseWidth;a>0;a--){
对于(intb=0;b=a-1&&b
保持两个指针
l
r
,这将决定您必须从哪个位置打印
*
,否则打印空间。每行之后,随着三角形在每行中向左和向右各增加一步,减少
l
并增加
r

只使用两个循环

int n = 5; // number of lines...
int l = n-1, r = n-1;
for(int i = 0; i < n; i++) {
    for(int s = 0; s < 2*n; s++) {
        if(s >= l && s<= r)
            System.out.print("*");
        else
            System.out.print(" ");
    }
    System.out.println();
    l--; r++;
}
两个循环

char[] s = "           ".toCharArray();
int start = 5;
int end = 5;
for (int i = 0; i < 5; i++) {
    for (int j = start; j <= end; j++) {
        s[j] = 'x';

    }       
    start--;
    end++;
    System.out.println(s);
}
char[]s=”“.toCharArray();
int start=5;
int-end=5;
对于(int i=0;i<5;i++){

对于(int j=start;j而不是对
循环使用两个
,我对
循环使用了1
,如果
语句则使用了1
(这不是循环)

输出是您如何询问的:

     x
    xxx
   xxxxx
  xxxxxxx
 xxxxxxxxx

您可能想看看这个:

public class CenterText {
    public static void main(String[] args){
        centerText(10, 'X');
    }

    public static void centerText(int noOfLines, char theChar){

        final int totalNoOfChars = noOfLines * 2;
        String totalSpaces = "";
        String chars = "";

        for (int i=0; i<totalNoOfChars; i++){
            totalSpaces += " ";
        }

        for (int j=1 ; j<=totalNoOfChars; j++){
            chars+=theChar;
            if(j%2==0){
                System.out.println(totalSpaces.substring(0, noOfLines-(j/2)) + chars);
            }       
        }   
  }


}
输出:

    *
   ***
  *****
 *******
*********
         XX
        XXXX
       XXXXXX
      XXXXXXXX
     XXXXXXXXXX
    XXXXXXXXXXXX
   XXXXXXXXXXXXXX
  XXXXXXXXXXXXXXXX
 XXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXX
输入:

centerText(7, '#');
输出:

      ##
     ####
    ######
   ########
  ##########
 ############
##############

为了好玩,让我们也有一个完全没有循环的解决方案:

static Stack<String> getStarryStrings (String lastString, Stack<String> result) {
    //First count the number of *'s in the string
    //From:http://stackoverflow.com/questions/275944/java-how-do-i-count-the-number-of-occurrences-of-a-char-in-a-string
    int starCount = lastString.length() - lastString.replace("*", "").length();
    if(starCount<1) return result;
    result.push(lastString);

    //Find first and last occurrences of *
    int fio = lastString.indexOf('*');
    int lio = lastString.lastIndexOf('*');

    //And replace them with white spaces
    StringBuilder nextLast = new StringBuilder(lastString);
    nextLast.replace(fio,fio+1," ");
    nextLast.replace(lio, lio + 1, " ");

    //And recurse...
    return getStarryStrings(nextLast.toString(),result);
}


public static void main(String[] args) {
    Stack<String> res = getStarryStrings("*********",new Stack<>());
    while(!res.isEmpty()) {
        System.out.println(res.pop());
    }
注意:
我确信这可以以一种更有效的方式来完成,以消除对
java.util.Stack
的需要。我唯一的标准是不使用循环。我让堆栈保持在那里,以显示解决方案的递归性质。使用
StringBuilder
代替堆栈可以很容易地改进。

欢迎使用堆栈溢出!看起来你可能在请求家庭作业帮助。虽然我们没有问题,但是请观察这些问题,并相应地编辑你的问题。(即使这不是作业,也请考虑建议。)<代码> iTrase.Lead(0, 10)。过滤器(I -> I % 2=0)。mapToObj(I-->流。生成((-)->”)限制((线-I)/ 2)。(Collectors.joining(“”)+Stream.generate(()->“x”).limit(1+i).Collectors(Collectors.joining()).forEachOrdered(System.out::println);
谢谢你,@JoeC!不过,这不是真正的家庭作业,而是我在检查一些关键算法和函数时偶然发现的东西(尽管我是一个普通程序员)。很好的方法,但是,我的任务是只使用两个for循环(在我注意到我忘记了这一点之后,我编辑了这个问题)。这在技术上可能吗?不过,我使用了一种类似的方法,使用了两个以上的循环。因此,您想只使用两个循环@John?@John检查我的编辑,您可以只使用一个循环来解决您的问题;)如果您对代码有任何疑问,请在注释部分回答。
         XX
        XXXX
       XXXXXX
      XXXXXXXX
     XXXXXXXXXX
    XXXXXXXXXXXX
   XXXXXXXXXXXXXX
  XXXXXXXXXXXXXXXX
 XXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXX
centerText(7, '#');
      ##
     ####
    ######
   ########
  ##########
 ############
##############
static Stack<String> getStarryStrings (String lastString, Stack<String> result) {
    //First count the number of *'s in the string
    //From:http://stackoverflow.com/questions/275944/java-how-do-i-count-the-number-of-occurrences-of-a-char-in-a-string
    int starCount = lastString.length() - lastString.replace("*", "").length();
    if(starCount<1) return result;
    result.push(lastString);

    //Find first and last occurrences of *
    int fio = lastString.indexOf('*');
    int lio = lastString.lastIndexOf('*');

    //And replace them with white spaces
    StringBuilder nextLast = new StringBuilder(lastString);
    nextLast.replace(fio,fio+1," ");
    nextLast.replace(lio, lio + 1, " ");

    //And recurse...
    return getStarryStrings(nextLast.toString(),result);
}


public static void main(String[] args) {
    Stack<String> res = getStarryStrings("*********",new Stack<>());
    while(!res.isEmpty()) {
        System.out.println(res.pop());
    }
    *    
   ***   
  *****  
 ******* 
*********