How do I compare a character in the range of an alphabet?

Asked

Viewed 339 times

-4

The question is this::
1)Help the university set up the divisions of the programming laboratory. For this, write an algorithm that reads the student’s name and tells which division he is respecting the rule below:
-students whose name begins with letters of To to K are in the D1;
-students whose name begins with the letters of L to N are in the D2;
-students whose name begins with the letters of The to Z are in the D3.
Tip: use the method charAt(posição)?

 public class ex4a3{
    public static void main (String[] args){
       String nome = JOptionPane.showInputDialog("Digite seu nome para
descobrir sua divisao:");
   char letra = nome.charAt(0); 

   if(letra >= "a" && letra <= "l"){
     JOptionPane.showMessageDialog(null,"Voce esta na divisao D1");
   }

   }
}
  • 2

    It would be better if you asked a question or stated what the problem is instead of passing the question as an exercise, as it would help in your understanding of the exercise, instead of receiving you ready without understanding and instead of learning need help every time you need to do an exercise.

1 answer

1

This question is about the guys you’re using.

"a" (note the double quotes, the character ") is a String.

'a' (note the quote/single quotes, the character ') is a char.

Note also that 'A' is different from 'a'. The basic characters (without accents, cedillas or other differential marks) have the numbering defined by the table ASCII.


Another alternative is to use regular expressions. Because of how you wrote the question, it seems like you are learning programming in Java, so you may not feel very comfortable with regular expressions. In Wikipedia you have an example of how to write regular expressions.

In the example below, you can play with the values of the variable nome to find out what matches a pattern (Pattern). In this case, the pattern I created fits with anything that starts with the letters of a to k, ignoring whether it is in high box or low box.

import totalcross.util.regex.Pattern;

public class Teste {

    public static void main(String[] args) {
        String nome = "luiz";
        Pattern pattern = new Pattern("^[a-k].*", "i");
        if (pattern.matches(nome)) {
            System.out.println("match");
        } else {
            System.out.println("not match");
        }
    }

}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.