Search code examples
javastringalphabetical

A Program that Checks Consecutive Letters - Java


I'm looking for help with a question I have. We just started learning simple java in our course after learning a tonne of C++.

One of our bonus missions for people who know code more than what was taught in class.

The mission is as follows: Write a function by the name lettersSeries which gets letters (one letter at a time, assume all letters are lower case) inputted from the user. The function stops accepting letters from the user once the user has inputted 3 consecutive letters. (Only for loops can be used without while loops)

Example: a -> b -> a -> c -> d -> e (Here is stops)

As far I don't know much and I would be happy if someone would help me with this... I tried some options but I have no idea how to trace the alphabet, and especially how to check if letters are consecutive...

Thanks!

public static void letterSeries() {
    //We create a scanner for the input
    Scanner letters = new Scanner(System.in);
    for(Here I need the for loop to continue the letters input) {
      //Here I need to know if to use a String or a Char...
      String/Char letter = next.<//Char or String>();
      if(Here should be the if statement to check if letters are consecutive) {
          /*
              Here should be
              the rest of the code
              I need help with
          */

Obviously, you could change the code, and not make my pattern, I would just be happier with an easier way!


Solution

  • Here's how I would tackle the problem, I'm going to let you fill in the blanks with this though so I don't do all of your homework for you.

    private void letterSeries() {
        Scanner scanner = new Scanner(System.in);
        char prevChar;
        char currChar;
        int amountOfConsecutives = 0;
        final int AMOUNT_OF_CONSECUTIVES = 2;
    
        for(;;) {
            // Take in the users input and store it in currChar
            // Check if (prev + 1) == currChar
                // If true, amountOfConsecutives++
                // If false, amountOfConsecutives = 0;
            // If amountOfConsecutives == AMOUNT_OF_CONSECUTIVES
                // Break out of the loop
        }
    }