• Empleos
  • Sobre nosotros
  • profesionales
    • Inicio
    • Empleos
    • Cursos y retos
  • empresas
    • Inicio
    • Publicar vacante
    • Nuestro proceso
    • Precios
    • Evaluaciones
    • Nómina
    • Blog
    • Comercial
    • Calculadora de salario

0

167
Vistas
How can I restrict the input char value?

I created simple calculator using switch case. When I enter the invalid operators, but it takes that value .And at last it gives the default switch case .How can I restrict it.

package calculator;

import java.util.*; public class Calculator {

public static void main(String[] args) {
    
    char operator;
    Double num1, num2, result;
    
    Scanner input = new Scanner(System.in);
    
    System.out.println("Enter the operator: +,-,*,/,% ");
    operator = input.next().charAt(0);
    
    //user input
    
    System.out.println("Enter the First Number:");
    num1 = input.nextDouble();
    
    System.out.println("Enter the Second Number:");
    num2 = input.nextDouble();
    

    switch (operator) {
        case '+': 
            result = num1+num2;
            System.out.println(num1+" + "+num1+" = " + result);
            break;
        case '-': 
            result = num1-num2;
            System.out.println(num1+" - "+num1+" = " + result);
            break;
        case '*': 
            result = num1*num2;
            System.out.println(num1+" * "+num1+" = " + result);
            break;
        case '/': 
            result = num1/num2;
            System.out.println(num1+" / "+num1+" = " + result);
            break;
        case '%': 
            result = num1%num2;
            System.out.println(num1+" % "+num1+" = " + result);
            break;
        default:
            System.out.println("Invalid operator");
        break;
    }
    input.close();

    
    
}

}

console output Enter the operator: +,-,*,/,% 7 Enter the First Number: 5 Enter the Second Number: 5 Invalid operator

about 3 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

if(Character.isDigit(c)){
   // what you want for true
}
else{
   // what you want for false
}
about 3 years ago · Santiago Trujillo Denunciar

0

This may help you. Java or any other programming languages run code sequentially. Here once the operator is entered you can check to proceed further for other statements. The logic of code how you write, that way it is executed.

So in this case, once you take value for operator check whether that operator is allowed in your case or not. If allowed then run the further code else not run that.

about 3 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recomiéndame algunas ofertas
Necesito ayuda