How to modify the last item in a string in Java?

2

People, I do not know if this is the question for doubt I have, but come on ... I want to get the following output: "V V V V V!".

First I created a simple algorithm just to simulate the output, no exclamation point at the end of the 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 anyone help me and give me a hint on how to make that exclamation mark at the end of the output? Right away, thank you!

    
asked by anonymous 07.07.2018 / 07:42

2 answers

4

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

  • Space if not the last
  • ! if this is the last

Example:

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

Output 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 " " .

You can also resolve without using a condition within for . To do this, you can change its limit so that it goes to the penultimate element, and writes the last element manually:

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

for now goes to the penultimate due to i < N - 1 , printing the elements followed by space, the last being printed out of for . However, N can not be 0 , because it will print V! . If you want to allow N to be 0 you have to type V! within if (n > 0) .

See these two examples on Ideone

    
07.07.2018 / 11:04
2

You can create a String to add the "V" in it and then add the point. So:

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);
    
07.07.2018 / 08:26