I am trying to write a code in java where i will ask user to enter an array of strings and calculate the cumulative length of all the strings combined combined.
The issue i am having is with inputing the strings into array. The code i have written is:
import java.util.*;
public class abcstring {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of strings");
int n = sc.nextInt();
String s[] = new String[n];
int length = 0;
for (int i = 0; i < n; i++) {
System.out.println("Enter the" +(i+1)+" sentance");
s[i] = sc.nextLine();
length = length + s[i].length();
}
System.out.println("The total lenght of all sentances in array is " + length);
}
}
For some reason the compiler skips through the first line of input like this:
Enter the number of strings:
3
Enter the1 sentance
Enter the2 sentance
hello world 12345
Enter the3 sentance
hello world 6789
The total lenght of all sentances in
array is 33
I have tried using next()
instead of nextLine()
but the question asked was for a string , i.e , including spaces. I tried using sc.next()Line.replace(' ','_')
because I had a feeling it was because of the spaces but still no use.