Search code examples
javafor-loopsubstring

This program gives either an error, or does not give the last letter, how should I fix it?


import java.util.Scanner;

class Assignment4 
{
  public static void main(String[] args) 
  {
        
    Scanner scan = new Scanner(System.in);
    System.out.println("Type the message to be shortened");
    String msg = scan.nextLine();
    msg = msg.toLowerCase();
    String alg1 = "";
    int vowelC = 0;
    int repeatC = 0;
    System.out.println("Algorithm 1");
    for (int i = 0; i<msg.length();i++){
      if(msg.substring(i-1,i).equals(" ")){
        alg1+=msg.substring(i,i+1);
      }
      else{
        if (msg.substring(i,i+1).equals("a") || msg.substring(i,i+1).equals("e") || msg.substring(i,i+1).equals("i") || msg.substring(i,i+1).equals("o") || msg.substring(i,i+1).equals("i")){
            vowelC++;
        }
        else if (msg.substring(i,i+1).equals(msg.substring(i-1,i))){
          repeatC++;
      }
        else{
        alg1+=msg.substring(i,i+1);
        }
      }
    }
    System.out.print(alg1);
    
  }
}

This results in a index out of range, -1. I understand why this is,that is not the issue, but when I tweak it by having the control of the for loop be i<msg.length()-1, it works but does not print the last letter. I also tried changing i to start at 1, but that cut off the first letter. Just not sure how to get the whole message with no error. Thanks!


Solution

  • What is the program trying to achieve?

    Your for loop is correct, you should have i = 0; i < length; i++

    Saying length-1 will stop one character short, as you noticed. For the substring calls, when you are using i-1 and ì+1 to refer to parts of the string, you should use if statements to check for the edge cases, when i=0 and when i=length, because both of those will result in out of range (e.g. results in attempts at accessing string[-1] and string[length], either of which don't exist).

    Or put the substring logic inside a try...catch and carry on through the out of range exception when err instanceOf OutOfRangeException