I started coding a couple months ago and I can't figure out how to work out this problem. Here is what is asked..
- Ask the user to type a phrase. Remove all the spaces from the phrase and turn all letters to upper case.
- Create a vector to store every letters of the phrase into one position, the vector must be the exact same size of the phrase.
- Show the content of the vector on screen.
I hit a wall were I can't start with a vector because of the remove spaces and upper case of item 1 but if I start with a normal String I don't know how to split letters by letters as asked in item 2.
Scanner entrada = new Scanner(System.in);
System.out.println("Type a phrase.");
String phrase = entrada.nextLine();
phrase = phrase.replace(" ", "");
phrase = phrase.toUpperCase();
System.out.println("");
System.out.println(phrase);
int characters = phrase.length();
System.out.println("The phrase has" characters "characters");
String[] vet = new String[characters];
for (int i = 0; i < characters; i ) {
CodePudding user response:
Your teaching materials sound a little out of date. @user16632363 is right about how to access each char
. Having done List<Character> allCharacters = new ArrayList<>();
earlier. you can now do:
int numChars = phrase.length();
for(int i = 0;i < numChars;i ) {
allChars.add(Character.valueOf(phrase.charAt(i)));
}
CodePudding user response:
phrase.toCharArray()
should do the trick.
In case you want the characters to be stored in a list:
List<Character> list = phrase.chars()
.mapToObj(c -> (char) c).collect(Collectors.toList());