【问题标题】:How to make print of Python in Java?如何在 Java 中打印 Python?
【发布时间】:2020-07-20 23:37:20
【问题描述】:

我最近一直在用 Java、Python 和 C 编写程序,同时还在学习 Ruby 和 Swift,我对使用不同语言制作打印函数很感兴趣,例如 Python 的 print、Java 的 System.out.println、C 的printf 和 C++ 的 cout。

我想做一些 Python 的“你好,(用户)”程序,如下所示:

user = input("What is your name? ")
print(f"Hello, {user}.")

并用Java编写一个具有相同打印功能的程序。

public static void main {
    Scanner user;
    print("What is your name? ");
    user = new Scanner(System.in);
    // print("Hello, ", user, ".");
    print(f"Hello, {user}.")
}

我想使用 f 格式在 print 函数中添加变量而不是串联(Java 程序中的注释)。除了以前的形式,我还不知道该怎么做,所以我仍然没有尝试。这里可以使用 f 格式吗?它只能用不同的语言重新创建吗?还是我根本不用做这个功能?

【问题讨论】:

标签: java python


【解决方案1】:

你在 python 中这样做

print("hello {0} and welcome to {1}".format(user, something)) 
# 0 is the index of the variable just like a list

这是在java中

System.out.println(String.format("A String %s %2d", user, intVar); 
// Its print-L-n not print-i-n
// you can use this in python too %s for strings and %d for integers

Python也是

print("%s is %d y/o" %(name, age))

%s - 字符串(或任何具有字符串表示的对象,如数字)和迭代器

%d - 整数

%f - 浮点数

%.f - 点右侧具有固定位数的浮点数。

%x/%X - 十六进制表示的整数(小写/大写)

而python中的f后缀并不重要,如果想知道的话,看看这个

https://www.python.org/dev/peps/pep-0498/

【讨论】:

    【解决方案2】:

    给定 Python 代码

    user = input("What is your name? ")
    print(f"Hello, {user}.")
    

    Java 等价物是

    public static void main(String[] args) {
        try (Scanner scanner = new Scanner(System.in)) {
            System.out.print("What is your name? ");
            String user = scanner.nextLine();
            System.out.printf("Hello, %s.%n", user);
        }
    }
    

    要打印格式化字符串,您可以使用printf 方法,您可以使用格式字符串,如Formatter classFormat string syntax 部分所述。

    所谓的格式化字符串文字(f-strings)仅在 Python 3.6 (PEP 498) 中引入,并且没有与它们对应的 Java(截至最新的 Java 14 版本)。

    (Java 也有一个MessageFormat,它使用不同的格式约定,另见What's the difference between MessageFormat.format and String.format

    【讨论】:

      【解决方案3】:

      在Java中没有这样的方法来制作打印功能,但是你的代码相当于:

      public static void main(String[] args) {
          System.out.print("What's your name? ");
          Scanner name = new Scanner(System.in);
          System.out.println("Hello, " + name);
      }
      

      然而,一个更可能的方式来制作一个打印功能是这样的:

      static void print(String a) {
          System.out.println(a)
      }
      

      是的,有连接而不是 f 字符串,但这就是我所能提供的。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-11-06
        • 2012-07-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多