Reputation: 67
my program has to print words backward with upper cases and at the end of every line print a dot. Can you please help me with deleting the last whitespace before the dot?
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int pocet = sc.nextInt();
sc.nextLine();
for (int i = 0; i < pocet; i++) {
String veta = sc.nextLine();
String veta2=veta.replaceAll("\\s+"," ");
String[] words = veta2.split(" ");
String result = "";
for (int j = 0; j<words.length;j++){
for (int k = words[j].length(); k > 0; k--) {
result = result + words[j].substring(k - 1, k);
}
words[j] = result;
result = "";
//return result.replaceAll("\\s+$", "");
}
words[words.length-1]= words[words.length-1];
System.out.println();
for (int j =0; j<words.length; j++){
char whitespace = ' ';
System.out.print(words[j].toUpperCase()+whitespace);
}
}
System.out.print(".");
System.out.println();
}
}
Thanks
Upvotes: 1
Views: 82
Reputation: 66
public static void main(String[] args) { Scanner in = new Scanner(System.in);
System.out.printf("Please insert number of lines you want to enter: ");
String[] input = new String[in.nextInt()];
in.nextLine();
for (int i = 0; i < input.length; i++) {
input[i] = in.nextLine();
}
String output = null;
for(int i=0;i<input.length;i++) {
output="";
String[] lst = new String[input[i].split(" ").length];
lst = input[i].split(" ");
for(int j = lst.length-1; j >= 0; j--) {
output+=(j==0)?lst[j]+".":lst[j]+" ";
}
System.out.println(output);
}
}
Upvotes: 0
Reputation: 14572
Just use String.join
to concatenate every String
separated by the CharSequence
you want (here a space) instead of that for loop.
String wordString = String.join(" ", words);
There, you won't need to remove anything. You still need to do an uppercase on the result before printing it.
wordString = wordString.toUpperCase()
System.out.println(wordString);
Upvotes: 0
Reputation: 1047
Replace your for by the code below:
for (int j =0; j<words.length; j++){
char whitespace = ' ';
System.out.print(words[j].toUpperCase());
if (j < (words.length - 1)) {
System.out.print(whitespace);
}
}
That way, you will add a whitespace except for the last word of your array
Upvotes: 1