vendredi 29 décembre 2017

Struggling with compare last 2/3/4 characters Java (repl.it 018 - Conditional Statement Practice 4)

Dear Stackoverflow community I am Struggling with one task on repl.it (018) Conditional Statements 4

So they want me to do that :

Instructions from your teacher: For you to do:

Given a string variable "word", do the following tests

If the word ends in "y", print "-ies" If the word ends in "ey", print "-eys" If the word ends in "ife", print "-ives" If none of the above is true, print "-s" No more than one should be printed.

and my code looks like this :

import java.util.Scanner;

class Main {
  public static void main(String[] args) {
    Scanner inp = new Scanner(System.in);
    System.out.print("In:");
    String word = inp.nextLine();
    //DO NOT CHANGE ABOVE CODE!  Write your code below

    if(word.endsWith("y"){
      System.out.println("-ies");
    }
    else if(word.endsWith("ey")){
      System.out.println("-eys");
    }
    else if(word.endsWith("ife")){
      System.out.println("-ives");
    }
    else{

      System.out.println("-s");
    }
  }
}

When I run it for example my input is :Hey

and of course my code will go through the code and see if the first statement is correct and yes it is equal because y = y at the end and that is WRONG!

My question is how can i let my code compare the last 2 or 3 characters so it will print out the right value when I input Hey.

If I input Hey it should print out :

-eys and not -ies

Ty

1 commentaire:

  1. Change the order of your if statements. Put the if(word.endsWith("y") statement at last and if(word.endsWith("ife")) at first. It will work fine for all cases.

    RépondreSupprimer