'Show how many characters there are in each element in an array (based on scanner input)
This is an assignment for school that I've been trying for way too long. I know how to print the total character count (as seen in the code). For example, entering Joe and Jane would result in [7]. How can I make it print [3, 4] or how long each name is?
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Enter the length of the array:");
int length = s.nextInt();
String[] myArray = new String[length];
String input;
int allChar = 0;
System.out.println("Enter the elements of the array:");
for (int i = 0; i < length; i++) {
myArray[i] = s.next();
}
System.out.println(Arrays.toString(myArray));
input = Arrays.toString(myArray);
for (int charCount = 0; charCount < input.length(); charCount++) {
if (Character.isLetter(input.charAt(charCount))) {
allChar++;
}
}
System.out.println("Total Characters: " + allChar);
}
Solution 1:[1]
How can I make it print [3, 4] or how long each name is?
You could create an array of integers to store the lengths of the names int[] nameLengths = new int[length]; and then fill this array according to your requirements (using String::length() or counting only letters in each name) along with incrementing the total allChars.
Then print the contents of nameLengths array using Arrays.toString.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Nowhere Man |
