import java.util.*;
class App {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a String: ");
String words[] = in.nextLine().split(" ");
for (int i = 0; i < words.length; i++) {
if (i % 2 == 0) {
System.out.print(words[i].substring(0, 1) + ". ");
} else {
System.out.print(words[i] + " ");
}
}
in.close();
}
}
Do this program without using array and split
import java.util.*;
class App {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a String: ");
String line = in.nextLine();
boolean space = true;
boolean first = false;
for (Character letter : line.toCharArray()) {
if (letter == ' ') {
System.out.print(letter);
space = !space;
first = false;
} else if (space) {
if (!first) {
System.out.print(letter + ".");
first = true;
}
} else {
System.out.print(letter);
}
}
System.out.println();
in.close();
}
}
Comments
Leave a comment