lundi 16 novembre 2020

Script skipping if-statement Java while using .equals

import java.util.Scanner;

public class Main
{
    public static void main(String[] args) 
    {
        String sentence;
        String before= "";
        String after= "";
        String letter;
        int wordlength;
        int lettercount=0;
        Scanner reader= new Scanner(System.in);
        System.out.println("Please enter a sentence");
        sentence= reader.nextLine();
        wordlength= sentence.length();
        System.out.println("What letter would you like to look for?");
        letter= reader.nextLine();
        for(int count=0; count<=wordlength; count++)
        {
            if(sentence.substring(count).equals(letter))// This Gets skipped for some reason
            {
                lettercount++;
                before= before+" "+(sentence.substring(count-1));
                after= after+" "+(sentence.substring(count+1));
            }
        }
        System.out.println("You entered "+sentence);
        System.out.println(letter+" appeared "+lettercount+" times");
        System.out.println("Before "+letter+" "+before);
        System.out.println("After "+letter+" "+after);
    }
}

The code is supposed to take a sentence, then ask for a letter and figure out how many times that letter comes up in the sentence, then print them out to the screen with the letters that came right before and after that letter. I know I didn't phrase that well, sorry.

Could anyone please help me with this?

Aucun commentaire:

Enregistrer un commentaire