在println语句中使用字符串和变量

时间:2011-10-03 22:14:33

标签: java

我正在编写一个程序,通过询问用户的英寸和英尺高度来找到用户的理想体重。到目前为止,除了最终陈述之外,一切看起来都不错,其中我向用户返回男性和女性的平均体重,并告诉他们他们的体重范围在15%之间。这是给我一个问题的代码:

System.out.println("For a male, the height " + foot "' " +
                   inches + "/""" + " and it's ideal weight is " + 
                   mWeight + "lbs. Anything between " + minMaleLb +
                   "lbs and " + maxMaleLb + "lbs is okay.");
System.out.println("For a female, the height " + foot "' " +
                   inches + "/""" + " and it's ideal weight is " + 
                   fWeight + "lbs. Anything between " + minFeMaleLb +
                   "lbs and " + maxFeMaleLb + "lbs is okay.");

以下是编译时收到的错误:

File: C:\Users\###\Java\IdealWeight.java  [line: 26]
Error: C:\Users\###\Java\IdealWeight.java:26: ')' expected
File: C:\Users\###\Java\IdealWeight.java  [line: 27]
Error: C:\Users\###\Java\IdealWeight.java:27: not a statement
File: C:\Users\###\Java\IdealWeight.java  [line: 27]
Error: C:\Users\###\Java\IdealWeight.java:27: ';' expected
File: C:\Users\###\Java\IdealWeight.java  [line: 29]
Error: C:\Users\###\Java\IdealWeight.java:29: not a statement
File: C:\Users\###\Java\IdealWeight.java  [line: 29]
Error: C:\Users\###\Java\IdealWeight.java:29: ';' expected
File: C:\Users\###\Java\IdealWeight.java  [line: 31]
Error: C:\Users\###\Java\IdealWeight.java:31: ')' expected
File: C:\Users\###\Java\IdealWeight.java  [line: 32]
Error: C:\Users\###\Java\IdealWeight.java:32: not a statement
File: C:\Users\###\Java\IdealWeight.java  [line: 32]
Error: C:\Users\###\Java\IdealWeight.java:32: ';' expected
File: C:\Users\###\Java\IdealWeight.java  [line: 34]
Error: C:\Users\###\Java\IdealWeight.java:34: not a statement
File: C:\Users\###\Java\IdealWeight.java  [line: 34]
Error: C:\Users\###\Java\IdealWeight.java:34: ';' expected
File: C:\Users\###\Java\Weight.java  [line: 30]
Error: C:\Users\###\Java\Weight.java:30: reached end of file while parsing
File: C:\Users\###\Java\Weight.java  [line: 34]
Error: C:\Users\###\Java\Weight.java:34: reached end of file while parsing

有人可以向我解释代码有什么问题,我该如何解决这个问题呢?

3 个答案:

答案 0 :(得分:18)

问题是你错误地引用了你的报价;应该是

... + "\"" + ...

用于引号。

编辑:正如JB Nizet在评论中指出的那样,+之后你错过了foot

此外,您可以使用

进一步简化该表达式
... + "\" and the ideal weight is " + ...

而不是连接两个单独的字符串。

答案 1 :(得分:14)

通过所有这些连接,我会使用System.out.format(format, args);

来提升
System.out.format("For a male, the height %d' %d\" and its ideal weight is %dlbs. Anything between %dlbs and %dlbs is okay.",
    foot, inches, mWeight, minMaleLb, maxMaleLb);

您还有拼写错误:

and it's ideal weight is

应该是

and its ideal weight is
当以占有形式使用时,“它”没有撇号(即不是“它的”)

答案 2 :(得分:1)

"/"""位看起来不对,可能会关闭解析器。也许您打算使用"\""(甚至更简单,'"'