Problem to validate the input from the user in java calculator

java input validation loop
java input validation numbers only
validating string input java
input validation java code
validate user input using java chars and strings
asking the user for input until they give a valid response java
validating user input and debugging
how to test user input in java

So I'm writing a code for a calculator in Java as a homework and I wanted to include an else statement in the end where if the user didn't input a valid operator, you get an error msg. Problem is that even when I input a valid operator, it prints the result and then the else error msg. Any help would be appreciated.

public class Main {

    public static void main(String[] args){

        Scanner inputi=new Scanner(System.in);
        double num1,num2;
        char operator;

        System.out.println("Please enter the first number: ");
        num1=inputi.nextDouble();
        System.out.println("Please enter the second number: ");
        num2=inputi.nextDouble();

        Scanner oper=new Scanner(System.in);
        System.out.println("Please enter the operator, the operators are +,-,*,/,%");
        operator = oper.next().charAt(0);

        if(operator== '+') { 
            System.out.println("The sum of these numbers is: "+(num1+num2));
        }
        if(operator=='-') {
            System.out.println("The diff of these numbers is: "+ (num1-num2));       
        }
        if(operator=='*') {
            System.out.println("The result of this multiplication is: "+(num1*num2));
        }
        if(operator=='/') {
            System.out.println("The division is: "+(num1/num2));
        }
        if(operator=='%') {
            System.out.println("The module is: "+(num1%num2));    
        }             
        else {
            System.out.println("Please just pick an operator..");

        }
   }

}

I'd recommend using switch instead:

     switch (operator) {
        case '+':
            System.out.println("+");
            break;
        case '-':
            System.out.println("-");
            break;
    /* Other operators */
        default:
            System.out.println("Please just pick an operator..");
    }

Solved: JAVA Add Validation To An Old Project (for Example , Answer to JAVA Add validation to an old project (for example the Area and Perimeter Calculator) This is what it should look like: Welcome to the Area and Perimeter Calculator. Enter length: ten. Error! Invalid get the input from the user The main idea here is to find the exception thrown by Scanner when a token retrieved does not match the expected type. If you enter a wrong input in your code, you would see java.util.InputMismatchException shown in the console.

You have "if if if if else" you want "if else if else if else". Your one else currently only applies to the if (operator == '%')

Input Validation – CS2 – Java, Any input that comes into a program from an external source – such as a user typing Failure to validate input can lead to serious security risks such as integer The check digit is determined by a calculation based on the remaining digits – if� Hi I am encountering a problem with a uni project I am working on. I am trying to validate the input so that the BookID that is entered when attempting to loan the book, is only valid if it exists in the array named 'BookList'. At the minute I have it working so that it validates it to make sure that an integer is entered, and not letters or

Try 'else if':

 if(operator== '+') { 
            System.out.println("The sum of these numbers is: "+(num1+num2));
        }
else if(operator=='-') {
            System.out.println("The diff of these numbers is: "+ (num1-num2));       
        }
else if(operator=='*') {
            System.out.println("The result of this multiplication is: "+(num1*num2));
        }
else if(operator=='/') {
            System.out.println("The division is: "+(num1/num2));
        }
else if(operator=='%') {
            System.out.println("The module is: "+(num1%num2));    
        }             
        else {
            System.out.println("Please just pick an operator..");

However, a switch statement would be clearer:

switch(operator) {
 case '%': 
  System.out.println("The module is: "+(num1%num2));    
  break; 
 default:
  System.out.println("Please just pick an operator..");
}

Java Tutorial - 11 - Validating User Input, In this Video I will be showing you how to validate user input, to avoid mis matching variables Duration: 7:06 Posted: Feb 28, 2013 So if a user is making a request with a bad input, (s)he will still have to wait unnecessarily. Alternatively, if a validation prevents that request from being executed, this time can be saved. Data / Bandwidth – Nowadays, a lot of users tend to use applications on the go, which in turn consumes their cellular data.

The problem here is that you are not fully understanding the if else-if else statements.

The "If" means: if this conditional statement is true then execute the code to follow in the brackets.

The "If-else" means: if the statements above (if and else-if) are not true then execute this code.

The "else" means: if the preceding statement above (if or else-if) are not true then execute this code.

Given this, I'm sure not that you can see your error. All of your "if" statements are evaluating to if this condition then do this. Whereas you really wanted, to use "else-if" where if this is true then only execute the following code with the exclusion of the rest of the conditionals. You are correct in having an else clause pick up the default, however since you are not using "else-if" it really is compiling down to if this statement is not true, (the statement right before your else clause):

    if(operator=='%') {
        System.out.println("The module is: "+(num1%num2));    
    }            

Then execute the else statement, which is not what you want.

I would recommend really figuring out what your code actually compiles down to in terms of machine instructions.

Java Program to Make a Calculator using Switch Case, In this Program we are making a simple calculator that performs addition, subtraction, multiplication and division based on the user input. then display an error message to user * */ default: System.out.printf("You have entered wrong Random Number � first n prime numbers � Disp prime Numbers � Check Prime number� this calculator is not very useful for the user since it cannot take any user input. test data, as well as "real" user input, should come as run time input. this may be from the command line, from an API call or from some kind of UI. havong the input specified at run time will allow you to modify the test data without need for recompile.

Simple Java calculator with two operands, Delaying the validation of input by carrying around the String values of supposed of the Scanner class that helps you pre-validate the user input. I see some problems with your code: It is not DRY, you calculate results that� TOP Interview Coding Problems/Challenges Run-length encoding (find/print frequency of letters in a string) Sort an array of 0's, 1's and 2's in linear time complexity

Evaluating arithmetic expressions, entire line of input that the user types, thus grabbing the entire expression at once. This solves the problem of separating the input into individual elements we can manipulate. The following Java class implements this data structure. above, we have all of the pieces we need to implement an expression calculator. To validate input the Scanner class provides some hasNextXXX() method that can be use to validate input. For example if we want to check whether the input is a valid integer we can use the hasNextInt() method. In the code snippet below will demonstrate how to validate whether the user provide a positive integer number. The program will repeat

Java Program to Check Whether a Number is Even or Odd [if-else , In this program, you'll learn to check if a number entered by an user is even or odd. This will be done using ifelse statement and ternary operator in Java. Now, to check whether num is even or odd, we calculate its remainder using� Java User Input. The Scanner class is used to get user input, and it is found in the java.util package. To use the Scanner class, create an object of the class and use any of the available methods found in the Scanner class documentation. In our example, we will use the nextLine() method, which is used to read Strings:

Comments
  • Oh, I didn't know that. The code works great now, so very kind. Thanks a bunch :]