【问题标题】:How to Trim the empty last line from the output before the testing of program?如何在程序测试之前从输出中修剪空的最后一行?
【发布时间】:2021-05-10 11:24:01
【问题描述】:

我正在尝试解决 HackerRank 的一个特定问题。

根据问题,输出末尾的额外行应该在那里,并在与测试用例的预期输出进行比较之前被修剪。

    import java.io.*;
    import java.util.*;

    public class Person {
    private int age;    

    public Person(int initialAge) {
    // Add some more code to run some checks on initialAge
              age  = initialAge;
              if (age<0){
                    age = 0;
                    System.out.println("Age is not valid, setting age to 0");
              }
    }

    public void amIOld() {
    // Write code determining if this person's age is old and print the correct statement:
    if (age<13) {
        System.out.println("You are Young");
    }
    else if(age>=13 && age<18){
        System.out.println("You are a teenager");
    }
    else{
        System.out.println("You are old");
    }
    }

    public void yearPasses() {
    // Increment this person's age.
            age = age + 1;
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int T = sc.nextInt();
        for (int i = 0; i < T; i++) {
            int age = sc.nextInt();
            Person p = new Person(age);
            p.amIOld();
            for (int j = 0; j < 3; j++) {
                p.yearPasses();
            }
            p.amIOld();
            System.out.println();
            }
    sc.close();
   }
   }
 

这是我的输出
输出:
1 年龄无效,设置年龄为0
2 你还年轻
3 你还年轻
4
5 你还年轻
6 你是个少年
7
8 你是个少年
9 你老了
10
11 你老了
12 你老了
13

预期输出
输出:
1 年龄无效,设置年龄为0
2 你还年轻
3 你还年轻
4
5 你还年轻
6 你是个少年
7
8 你是个少年
9 你老了
10
11 你老了
12 你老了

【问题讨论】:

  • 你不能检查一个字符串是否等于“”吗? str == ""
  • @olimpiabaku 这不是您在 java 中比较字符串的方式。请看How do I compare Strings in Java?

标签: java class instance


【解决方案1】:

一旦你写了它,你就写了它。你无法取消它。在确定需要它之前,您必须不要运行 System.out.println() 行。

【讨论】:

  • 你能解释一下吗
【解决方案2】:

在循环的开头而不是结尾处打印分隔符:

// First iteration, don't print anything.
String separator = "";
for (int i = 0; i < T; i++) {
    System.out.print(separator);

    // Change separator so that you print a line separator on subsequent iterations.
    separator = System.lineSeparator();

    // Rest of loop body.
}

【讨论】:

    猜你喜欢
    • 2011-10-08
    • 1970-01-01
    • 1970-01-01
    • 2014-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多