How to modify the last item of a sequence in Java?

Asked

Viewed 51 times

2

Guys, I don’t even know if that’s the question I have to be sure about, but come on... I want to get the following output: "V V V V!".

First I created a simple algorithm just to simulate the output, no exclamation mark at the end of output:

public static void main(String[] args){

    int N, i;
    Scanner ler = new Scanner(System.in);

    N = ler.nextInt();
    for(i = 0; i < N; i++){
        System.out.print("V ");
    }
}

Can someone help me and give me a hint how to make that exclamation mark at the end of the exit? From now on, thank you very much!

2 answers

4


A very simple way to solve it is with a condition within the for, which writes the element followed by:

  • Space if not the last
  • ! if it’s the last

Example:

for(i = 0; i < N; i++){
    System.out.print("V" + (i < N - 1 ? " " : "!"));
}

Exit to N of 5:

V V V V V!

The condition i < N - 1 indicates if the element is not the last, and therefore writes the " ".

It can also solve without using a condition within the for. For this you can change its limit so that it goes to the penultimate element, and write the last one manually:

for(i = 0; i < N - 1; i++){
    System.out.print("V ");
}
System.out.println("V!");

The for now goes down to the last i < N - 1, printing the elements followed by space, the latter being printed outside the for. However, in this way the N can’t be 0, because it will print V!. If you want to allow the N may be 0 have to write the V! within a if (n > 0).

See these two examples in Ideone

  • Thank you! Both solutions worked very well! I used the second one. See you more!

2

You can create a String to add the "V" to it and then add the dot. Thus:

N = ler.nextInt();
String str = "";

    for(i = 0; i < N; i++){
        srt = str.append("V ");
        System.out.print("V ");
    }

str = str.append("!");
System.out.println(str);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.