Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

144
Visualizações
How can I assign a certain case to execute the same code as another case in a java switch statement?

What I'm trying to do is allow a user to input different variations of a string(by that I mean, a user could enter either "Calculator", "Calc", "calculator", etc.), and still get the same code executed so I don't have to copy it into each case I want to do the same thing. i.e.

switch(input) {
    case "string1":
        statement 1;
        break;
    case "string2":
        statement 1;
        break;
    case "string3":
        statement 2;
        break;
    case "string4":
        statement 2;
        break;
    default:
        break;

Is there an easy way to do this, other than writing the same statement for each case?

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

A comment gave me the term I was looking for, so I searched it up and found the answer myself. I now know that I can combine cases by putting the case label with just the colons above the next case, that has the statement to be run in both cases. i.e.

switch(input) {
    case "string1":
    case "string2":
        statement1;
        break;
    case "string3":
    case "string4":
        statement2;
        break;
    default:
        break;

This gives my desired output. Thank you, Dave Newton!

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda