Print multiple lines output in java without using a new line character

前端 未结 9 1909
轮回少年
轮回少年 2020-12-18 15:40

this is one of the interview question. I am supposed to print multiple lines of output on command line, without using the newline(\\n) character in java. I trie

相关标签:
9条回答
  • 2020-12-18 15:58

    The ASCII value of new Line is 10. So use this

    char line = 10;
    System.out.print("1" + line + "2" + line ......);
    
    0 讨论(0)
  • 2020-12-18 16:01

    Probably cheating based on the requirements, but technically only 1 println statement and no loops.

    public int recursivePrint(int number)
    {
      if (number >=5 )
        return number;
      else
        System.out.println(recursivePrint(number++));
    }
    
    0 讨论(0)
  • 2020-12-18 16:03

    No loops, 1 println call, +flexibility:

    public static void main (String[] args) {
        print(5);
    }
    
    final String newLine = System.getProperty("line.separator");
    public void print(int fin) {
        System.out.println(printRec("",1,fin));
    }
    private String printRec(String s, int start, int fin) {
        if(start > fin)
            return s;
        s += start + newLine;
        return printRec(s, start+1, fin);
    }
    
    0 讨论(0)
  • 2020-12-18 16:04

    If you're just not allowed of using \n and println() then you can get the systems line.separator, e.g.

    String h = "Hello" + System.getProperty("line.separator") + "World!"
    

    Hope this helped, have Fun!

    0 讨论(0)
  • 2020-12-18 16:07

    You can do it recursively:

    public void foo(int currNum) {
      if (currNum > 5) 
        return;
      println(currNum);
      foo(currNum + 1);
    }
    

    Then you are only using a single println and you aren't using a for or while loop.

    0 讨论(0)
  • 2020-12-18 16:11

    There are many ways to achieve this...

    One alternative to using '\n' is to output the byte value for the character. So, an example to print out your list of the numbers 1-5 in your example...

    char line = (char)10;
    System.out.println("1" + line+ "2" + line+ "3" + line + "4" + line+ "5");
    

    You could also build a byte[] array or char[] array and output that...

    char line = (char)10;
    char[] output = new char[9]{'1',line,'2',line,'3',line,'4',line,'5'};
    System.out.println(new String(output));
    
    0 讨论(0)
提交回复
热议问题