Java Code for Average Word Length and Average Sentence Length

后端 未结 1 1977
别跟我提以往
别跟我提以往 2021-01-15 04:22

Ok, so, I\'m a relatively new programmer and I\'m having major difficulty with this assignment. The assignment is to create a 2 class java code that will read in a file, a b

相关标签:
1条回答
  • 2021-01-15 05:23

    Look at this section:

    for(int c = 0; c < line.length(); c++){
      char ca = line.charAt(c);
      if((line.charAt(ca) == '.')|| (line.charAt(ca) =='!') || (line.charAt(ca) =='?')); 
      sentencecount++ ;}
    

    There are two problems here:

    1. The variable "ca" is the character at index c. But you're passing "ca" to line.charAt... Java is "helpfully" converting the char to an int, and trying to return the character at that index. That's not what you want, and it's why you're getting the StringIndexOutOfBoundsException.

    2. You probably want to increment sentenceCount only if the expression is true, right? That's not what the code says. This "if" statement has no body (because of the semicolon on the same line as the "if" statement). A good practice, especially for beginners, is to always use curly braces to enclose the body of if blocks, even if they are only one line.

    As for the IllegalFormatConversionException, it's telling you that %5.3f is not a valid conversion pattern for an integer ("f" is for floats and doubles). fifteenplus is declared as an int; is that the correct type? If so, you can just print it like this:

    System.out.println("words of 15 or more characters length: " + fifteenplus);
    

    If you mean for it to be a percentage like all the other lines, then you should declare it as a float or double (generally you should prefer doubles over floats because doubles offer more precision and the performance difference is usually insignificant).

    One final point: Isn't it strange that all of your percentages end in .000%? In Java, dividing an int by an int always gives you an int. If you want a floating point result, you must cast one of the arguments to a float or double, like this:

    int a = 1;
    int b = 2;
    double result = (double) a / b;
    

    Try that with and without the cast to double to see the difference.

    0 讨论(0)
提交回复
热议问题