0

I am trying to solve a particular problem at HackerRank.

According to the Question, The extra line at the end of the output is supposed to be there and is trimmed before being compared against the test case's expected output.

    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();
   }
   }
 

This is my output
Output:
1 Age is not valid, setting age to 0
2 You are Young
3 You are Young
4
5 You are Young
6 You are a teenager
7
8 You are a teenager
9 You are old
10
11 You are old
12 You are old
13

expected output
Output:
1 Age is not valid, setting age to 0
2 You are Young
3 You are Young
4
5 You are Young
6 You are a teenager
7
8 You are a teenager
9 You are old
10
11 You are old
12 You are old

  • Can't you check if a String is equal to ""? `str == ""` – olimpiabaku May 10 '21 at 11:32
  • 1
    @olimpiabaku this is not how you compare strings in java. Please see [How do I compare Strings in Java?](https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – maloomeister May 10 '21 at 11:35

2 Answers2

0

Once you write it, you wrote it. You can't unwrite it. You'd have to not run the System.out.println() line until you are sure that you want it.

rzwitserloot
  • 85,357
  • 5
  • 51
  • 72
0

Print the separator at the start of the loop, rather than at the end:

// 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.
}
Andy Turner
  • 137,514
  • 11
  • 162
  • 243