Why are you not entering the if?

Asked

Viewed 88 times

0

I want to perform an operation if the 2° position of a string is higher, but it is not entering the if, and I think the if is not correct.

Example:

digital user 4A6 then in this string the 2° position is uppercase. How do I say that the position the user typed is uppercase?

Follow the code to clarify

public class JogoMatematica {

public static void main(String[] args) {

    Scanner entrada = new Scanner(System.in);

    System.out.println("Quantidade de caso de teste: ");
    int qtd = entrada.nextInt();

    for (int i = 0; i <  qtd;  i++){ 
        System.out.println("Digite os 3 caracteres: "); 
        // exemplo de entrada 4A6. A letra "A" eh maiuscula
        String caractere = entrada.next(); 
        // pega o elemento da posicao 0
        int valorInt1 = Integer.parseInt(caractere.substring(0,1));
        // pega o elemento da posicao 2
        int valorInt2 = Integer.parseInt(caractere.substring(2)); 
        // pega o elemento na posicao 1
        // se a letra "A" for maiuscula entra no if 
        if(caractere.substring(1,2).toUpperCase().equals(caractere)){ 
             System.out.println("String maiuscula na posicao ");     
        } 

        }
  • You’re making the comparison of A with 4A6. Stringare immutable then caractere.substring(1,2) is creating a new object.

  • 1

    Try using in your last if char c = caractere.charAt(1);&#xA; if (Character.isUpperCase(c))

  • 1

    You’re comparing a substring with the whole input, here: if(caractere.substring(1,2).toUpperCase().equals(caractere))

1 answer

5


Your code is comparing character 2 with the full string typed by the user, so it will never work:

if(caractere.substring(1,2).toUpperCase().equals(caractere)){ 

What you need to do is just check if the second character is uppercase, for this you can use the method Character.isUpperCase. Your test would look like this:

if (Character.isUpperCase(caractere.charAt(1))) {
  ...
}

Browser other questions tagged

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