-2

My application is supposed to print the smaller value as either int or double, but i don't know how to configure my code to make my application print the smaller number as double or int, depending on the type of value that the user enters.

Ex. user enters 2.5 and 3.5, prints smaller number in double user enters 2 and 3, prints smaller number in int

import java.util.Scanner;

public class SmallerNumber{
public static int smallerNumber(int valOne, int valTwo){
    if (valOne < valTwo){
        return (valOne);
    }
    else{
        return (valTwo);  
    }
}
public static double smallerNumber(double valOne, double valTwo){
    if (valOne < valTwo){
        return (valOne);
    }
    else{
        return (valTwo);  
    }
}
public static void main(String[]args){
   Scanner in = new Scanner(System.in);

   System.out.print("Enter first value: ");
   int valOne = in.nextInt();
   System.out.print("Enter second value: ");
   int valTwo = in.nextInt();


   int smallerNum = smallerNumber(valOne, valTwo);
   System.out.println(smallerNum);
   double smallerNum2 = smallerNumber(valOne, valTwo);
   System.out.println(smallerNum2);
}

}

  • 1
    This is a bit confusing. You're reading ints in only but you *also* want to read in doubles? Part of your issue is [with this question](https://stackoverflow.com/q/13102045/1079354) but the other part is that you haven't finished writing this code... – Makoto Dec 13 '18 at 19:47

2 Answers2

0

When you write nextInt() you read the input as an integer value, hence the name. The return type of this method is defined as int and you save these values in int variables. When you call smallerNumber(valOne, valTwo); it will use the overloaded method which has int arguments.

When you want to use the smallerNumber(...); method with the double arguments you have to provide double values. This means you need to use nextDouble() calls to get double values from the input. After that the correct smallerNumber(...); overload will be used.

To determine if the user has entered an "integer" or "double" value without actually reading the value, you have to use the hasNextInt() or hasNextDouble() methods. Another way would be to always use nextDouble() and try to convert it to an integer value. If it is successful you can use the integer values to call the smallerNumber(int, int); method, otherwise call the smallerNumber(double, double); method.

Progman
  • 13,123
  • 4
  • 28
  • 43
0

I will do something like this. Read the input as double and then modulo 1 to see if its float or int

public static void main(String[]args)
{
 Scanner in = new Scanner(System.in);

 System.out.print("Enter first value: ");
 double valOne = in.nextDouble();
 System.out.print("Enter second value: ");
 double valTwo = in.nextDouble();
 if ((valOne % 1) == 0 && (valTwo % 1) == 0)
 // call the intmethod version
 else 
 // call the float/double method

}
Gauravsa
  • 5,551
  • 1
  • 13
  • 23