你能把变量写进去吗?详情请见

时间:2013-12-20 05:16:22

标签: java

有没有办法简化这个代码,可能会像写作然后变量然后再写一样?我的意思是一条线。

class tests {
public static void main(String args[]) {
    int david, mark, alex;
    david = 20;
    mark = 30;
    alex = 12;

        System.out.println("hey");
    System.out.print("I can't believe that mark is ");
    System.out.print(mark);
    System.out.print(" years old.. thank god alex and david are  ");
    System.out.print(alex);
    System.out.print(" and ");
    System.out.print(david);
    System.out.print("...");
 }

}

请注意,编写简单的东西需要多少System.out.print?无论如何还是要使用这些变量来简化这个吗?

5 个答案:

答案 0 :(得分:2)

你可以这样做:

System.out.println("hey\n I can't believe that mark is "+mark+" years old.. thank god alex and david are  "+alex+" and "+david+"...");

注意,因为您使用println(表示新行)“hey”,您需要在其中添加\n < / p>

答案 1 :(得分:2)

System.out.printf("hey%n I can't believe that mark is %s years old.. thank god alex and david are  %s and %s...",mark,alex,david);

答案 2 :(得分:1)

喜欢这个

StringBuilder sb = new StringBuilder();
sb.append("hey");
sb.append("\n");
sb.append("I can't believe that mark is ");
sb.append(mark);
sb.append(" years old.. thank god alex and david are  ");
sb.appendt(alex);
sb.append(" and ");
sb.append(david);
sb.append("...");
System.out.println(sb.toString());

如果您执行以下代码,则会给您带来很少的性能问题。

System.out.println("hey\n I can't believe that mark is "+mark+" years old.. thank god alex and david are  "+alex+" and "+david+"...");

每个'+'操作它将创建新的String对象。

使用StringBuilder进行字符串连接操作。您可以根据需要将更多字符串附加到StringBuilder。如果你想清除StringBuilder,请使用myStringBuilder.setLength(0);或者创建新的StringBuilder对象。

答案 3 :(得分:0)

在此方案中使用 String.format 方法。

int x = 10;
String name = "User1";

String result = String.format("Hi %s, this is your number %d",name,x);
System.out.println(result);

感谢。

答案 4 :(得分:0)

这样做

StringBuilder sb = new StringBuilder();
sb.append("hey\n").append("I can't believe that mark is ").append(mark).append(" years old.. thank god alex and david are  ").append(alex).append(" and ").append(david).append("...");

System.out.print(sb.toString());

出于性能原因,你真的不想使用“+”连接很多字符串。