hi guys im trying to capitalise the first letter of every string however it doesn't seem to work.
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
public class Main {
public static void main(String[] args) throws IOException {
InputStreamReader reader = new InputStreamReader(System.in, StandardCharsets.UTF_8);
BufferedReader in = new BufferedReader(reader);
String line = in.readLine();
while ((line = in.readLine()) != null) {
String output = line.substring(0, 1).toUpperCase() line.substring(1) " ";
System.out.println(output);
}
}
}
the system inputs a sentence like "stack overflow" and needs the output to be "Stack Overflow" so every letter is capital.
It seems to only put the same input, no change. i have searched everywhere online however most resources are only for the first string.
any help would be appreciated.
CodePudding user response:
A "simple" a.k.a. an overlooked typo is what you have at line no. 9.
Because of that typo, it reads the input then goes to the next line, skipping your while-loop.
I also saw that you can only capitalize the first letter of your first word, which is definitely not what you were planning to do.
Simply modify your code into:
public class Main {
public static void main(String[] args) throws IOException {
try(
InputStreamReader reader = new InputStreamReader(System.in, StandardCharsets.UTF_8);
BufferedReader in = new BufferedReader(reader)
){
String line;
while ((line = in.readLine()) != null) {
String output="";
for (String s:line.split(" ")) {
output = s.substring(0, 1).toUpperCase() s.substring(1) " ";
}
System.out.println(output);
}
}
}
}
I also noticed that you have several "leakages" into your code which is~ in other words, "bad practice" so the code looks a tad bit different.
CodePudding user response:
Try with this code.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
public class Main {
public static void main(String[] args) throws IOException {
InputStreamReader reader = new InputStreamReader(System.in, StandardCharsets.UTF_8);
BufferedReader in = new BufferedReader(reader);
String line = null;
String output = "";
while ((line = in.readLine()) != null) {
line = line.trim();
String[] lineSplitArr = line.split(" ");
for (String s : lineSplitArr) {
output = (s.substring(0, 1).toUpperCase() s.substring(1) " ");
}
System.out.println(output);
break;
}
}
}