【问题标题】:Trying to get output and prompt to appear on separate lines - Java试图获得输出并提示出现在不同的行上 - Java
【发布时间】:2022-08-17 21:17:00
【问题描述】:

我想让斐波那契数列和提示 \"Type 1 to continue\" 出现在单独的行上。我怎样才能做到这一点?

目前的输出将是这样的:

前 5 个数字的斐波那契数列:
0 1 1 2 3 输入 1 继续:

我希望它显示为:

前 5 个数字的斐波那契数列:
0 1 1 2 3
输入 1 继续:


import java.util.Scanner; //Import Package

// Fibonacci Series using Recursion
public class Homework {
    static void fib(int n) //fib(n) method 
  {
        int num1 = 0, num2 = 1;
  
        int counter = 0;
  
        while (counter < n) {
  
            System.out.print(num1 + \" \");
  
            // Swap
            int num3 = num2 + num1;
            num1 = num2;
            num2 = num3;
            counter = counter + 1;
        }
    }
    
    public static void main(String args[]) //main method
    {
    int n = 1;
        Scanner myObj = new Scanner(System.in);
        char cont;
        do {
            System.out.println(\"Enter the number: \"); //Ask user to enter the number (value of n)
            n = myObj.nextInt(); // Numerical input 
        try{
            if(n < 0)
            System.out.println(\"This program does not accept negative numbers\");
            
            else
            System.out.println(\"Fibonnaci Series for the first \" + n + \" numbers:\");
                fib(n); //Call fib(n) to generate Fibonacci Series

               }
            catch(IllegalArgumentException e){
                System.out.println(\"This program does not accept negative numbers\");
              }
            // call fib(n) to generate and print Fibonacci Series for n
            
        System.out.print(\"Type 1 to continue: \"); // Ask user to Type 1 to continue
        cont = myObj.next().charAt(0);
        
    } while(cont == \'1\');
    

    
}  

}

  • 只需在输出\"Type 1 to continue: \" 之前使用System.out.println()
  • 这是一个很好的例子,说明为什么在遇到您不想要或不期望的行为时,阅读您使用的方法的官方文档应该始终是第一步。简单地看一下printlnprint 方法的文档就会告诉你这两个方法之间的区别是什么,而且你可能自己解决了这个问题,而不是你写这个问题所花费的时间。
  • 或者您可以添加换行符:System.out.print(\"\\nType 1 to continue: \");

标签: java


【解决方案1】:

System.out.print() 将其参数打印到系统的输出流。 System.out.println() 也这样做,但在末尾添加了一个“新行”符号。

“新行”符号也可以手动编写为转义序列。转义序列是特殊的不可见字符,例如用于格式化。这些序列由单个反斜杠 \ 引入。 现在通常由\n 引入新行,尽管还有其他选项。

您现在有两个选择:

  1. System.out.println() 打印序列中的最后一个数字。
  2. "Type 1 to continue" 之前打印\n

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-14
    • 2016-04-23
    • 2016-06-19
    • 1970-01-01
    • 2020-11-24
    相关资源
    最近更新 更多