来自 String.format() 的非法转义字符

illegal escape character from String.format()

提问人:iEdit4Fun 提问时间:6/6/2023 最后编辑:AnonymousiEdit4Fun 更新时间:6/6/2023 访问量:112

问:

编辑:

当我尝试编译我的 Java 程序时,我收到“错误:非法转义字符”。

最小可重复示例:

public static void main(String... args) {
    String output = String.format("%7d\%7d\%5d\t%%5s\t%s", 1299.97, 465.64, 1963, "00694", "ATLAS CENTAUR 2");
}

预期输出:

 1299.97      465.64    1963      00694        ATLAS CENTAUR 2         

javac 的输出:

Main.java:6: error: illegal escape character
        String output = String.format("%7d\%7d\%5d\t%%5s\t%s", 1299.97, 465.64, 1963, "00694", "ATLAS CENTAUR 2");
                                           ^
Main.java:6: error: illegal escape character
        String output = String.format("%7d\%7d\%5d\t%%5s\t%s", 1299.97, 465.64, 1963, "00694", "ATLAS CENTAUR 2");
                                               ^
2 errors

如何解决此问题?

原来问题,可以忽略:

第 44 行出错,我不知道如何解决


Hi I am new to java programming. I want to write a java program to print out the satilites from a website. Error at line 44 and I don't know how to fix it. I'm not sure if I'm using the .format right. Can I please have some help?

This is the assignment:

作业 3 是:

编写 3 个函数:

apogee which takes 2 parameters, mean motion and eccentricity and returns the apogee in kilometers.

perigee which takes 2 parameters, mean motion and eccentricity and returns the perigee in kilometers.

launch year yyyy which takes an integer parameter, the 2 digit launch year, and returns an integer, the 4 digit launch year.

    hint: use the date for the 1st ever artificial satellite launch to write a function that will work until 2057

不要忘记偏心率的“假定小数点”。(在将提取的子字符串转换为双精度之前,使用 String 连接将前导“0.”预置到提取的子字符串中)。

它应该看起来像这样:

 1299.97      465.64    1963      00694        ATLAS CENTAUR 2         
  813.27      765.76    1964      00733        THOR AGENA D R/B        
  753.32      648.28    1964      00877        SL-3 R/B                
  799.01      704.45    1967      02802        SL-8 R/B                
  616.16      574.02    1968      03230        SL-8 R/B                
  .....................................................
java 编译器错误 语法错误 字符串格式化

评论

3赞 Jaromanda X 6/6/2023
三个问题:你把文本放在代码块中,使其难以阅读,并在这不是javascript时标记javascript,并链接了代码图片,而不是将代码放在问题中
0赞 Elliott Frisch 6/6/2023
不要将代码作为图像发布。格式字符串中应该包含的所有位置(假设您希望在输出中有一个实际值)。\%\\%\
0赞 iEdit4Fun 6/6/2023
我试图将其发布在文本框中,但没有用
0赞 iEdit4Fun 6/6/2023
我试图把它放在问题中,但没有用。我也尝试了\\%,但它不起作用,我仍然遇到错误
0赞 Anonymous 6/6/2023
欢迎使用 Stack Overflow。为了让这里的用户考虑您的问题,您需要将您的程序,或者更好的是,一个最小的可重现示例,粘贴到问题中并将其格式化为代码(有一个按钮)。并以相同的方式粘贴错误输出(格式化为代码以保留换行符)。并指出哪一行是第 44 行(该行)。System.out.println()

答:

1赞 Reilas 6/6/2023 #1

您可以查看格式化程序JavaDoc 上的格式说明符

实数值使用 %f
并且,整数值使用 %d

您可以使用以下命令根据需要获取类似的输出。

"%7f %7f %5d %5s %s"
1299.970000 465.640000  1963 00694 ATLAS CENTAUR 2

您可以使用 %.2f 指定比例,其中 .2 是比例。
而且,您可以通过在宽度前添加 0 来添加前导零。

"%7.2f %7.2f %5d %5s %s"
1299.97  465.64  1963 00694 ATLAS CENTAUR 2

评论

0赞 Reilas 6/7/2023
@OleV.V.,不用了,谢谢伙计。将您的评论带到其他地方。