Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can you use the sum method for both float and int using user input in JAVA?

So I am working on a project and my code works when I put a float or int in the first input and then add with an int in second input. But if I try to add a int in the first input and a float in the second input it does not work.

For example,
Enter the first number:
34.6
This input is of type float.

Enter the second number:
90
Your answer is: 124.6
The above works.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Below does not work.
Enter the first number:
90

Enter the second number:
34.7

Here is my code:

import java.util.Scanner;

// Basic Intro/ Refresher for Sums using User Input
public class BasicSums {

public static void main(String[] args) {
    
    // User input 
    Scanner input = new Scanner (System.in);
    System.out.println("Enter the first number: ");
    
    
    if (input.hasNextInt()) {
        int initial = input.nextInt();
        System.out.println("\nEnter the second number: ");
        int second = input.nextInt();
        
        System.out.println("Your answer is: " + Integer.sum(initial, second));
    
    //Considering the possibility of the user entering a decimal value  
    } else if (input.hasNextFloat()) {
        System.out.println("This input is of type float.\n");
        float first = input.nextFloat();
        System.out.println("Enter the second number: ");
        float second = input.nextFloat();   
        System.out.println("Your answer is: " + Float.sum(first, second));          
    } 
    
    
    
    }

}

>Solution :

In the if block for if (input.hasNextInt()) (i.e. the first input is an integer), you only try to read two ints (using input.nextInt()), so inputs with decimals will not be accepted for the second number.

One way to fix this is to use float second = input.nextFloat(); and just use the + operator to sum first and second.

Since integers can be considered real numbers with no fractional part, you can also simply read two floats (or doubles, for higher precision) and add them with the + operator.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading