如何限制单行打印的字符串数量

时间:2013-12-16 17:56:58

标签: java string

我希望能够输入字符串s和整数n,然后打印字符串s n次。我已经这样做了,但我希望每行只有2个字符串。 到目前为止,这是我的代码:

public static void main(String[]args){

    Scanner in = new Scanner(System.in);
    System.out.println("Please enter string: ");
    String s = in.nextLine();
    System.out.println("Please enter number: ");
    int n = in.nextInt();

    for(int j=0; j<n; j++){
        System.out.println(s);

    }

    if(n<0){
        System.out.println("error: number must be positive");
    }

}

我们说字符串为java,数字为6。我需要输出:

java java
java java
java java

5 个答案:

答案 0 :(得分:3)

使用模运算符(%)检查循环索引是否可被2整除。

    public static void main(String[]args){

    Scanner in = new Scanner(System.in);
    System.out.println("Please enter string: ");
    String s = in.nextLine();
    System.out.println("Please enter number: ");
    int n = in.nextInt();

    for(int j=1; j<n+1; j++){
        System.out.print(s);
        if (j%2==0)
            System.out.println("\n");
        else
            System.out.print(" ");
    }

    if(n<0){
        System.out.println("error: number must be positive");
    }

    }

编辑我将输出更改为使用print()而不是println()并添加了一个空格,因此输出格式化为您问题中的示例。还将for循环索引更改为一个,以便mod正常工作。

答案 1 :(得分:0)

在for循环中创建一个计数为2的简单计数器。到达两个之后。添加返回字符。

int count = 0;
for(int j=0; j<n; j++){
   System.out.print(s);
   count++;
   if (count == 2) {
      System.out.print("\n");
      count = 0;
   }
}

答案 2 :(得分:0)

public static void main(String[]args){

    Scanner in = new Scanner(System.in);
    System.out.println("Please enter string: ");
    String s = in.nextLine();
    System.out.println("Please enter number: ");
    int n = in.nextInt();

    for(int j=0; j<n; j++){

    // modified
     if(j%2==0 && j!=0){
        System.out.println("\n");
        }
     System.out.print(s);  // Should this not be print and not println 
         System.out.print(" ");

    // end of modification

    }

    if(n<0){
        System.out.println("error: number must be positive");
    }
}

答案 3 :(得分:0)

for(int j=0; j<n/2; j++){
        System.out.println(s+" "+s);
}

答案 4 :(得分:0)

试试此代码

public static void main(String[]args){

    Scanner in = new Scanner(System.in);
    System.out.println("Please enter string: ");
    String s = in.nextLine();
    System.out.println("Please enter number: ");
    int n = in.nextInt();

    for(int j=0; j<n/2; j++){
        System.out.print(s + " " + s + "\n");
    }
    if(n%2 == 1){
        System.out.print(s);
    }

    if(n<0){
        System.out.println("error: number must be positive");
    }
}