In: Computer Science
How do i remove the decimals out of the output? Do I need to int a new value, or use Math.round?
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
double numbers[] = new double[5];
inputArray(numbers);
maxNumber(numbers);
minNumber(numbers);
}
public static void inputArray( double[] numbers) {
Scanner in = new Scanner(System.in);
for(int i = 0; i < numbers.length; i++) {
numbers[i] = in.nextDouble();
}
}
public static void maxNumber(double[] numbers) {
double maxNum = numbers[0];
for(int i = 0; i < numbers.length; i++) {
if(numbers[i] > maxNum ) {
maxNum = numbers[i];
}
}
System.out.println("Max: "+maxNum);
}
public static void minNumber(double[] numbers) {
double minNum = numbers[0];
for(int i = 0; i < numbers.length; i++) {
if(numbers[i] < minNum ) {
minNum = numbers[i];
}
}
System.out.println("Min: "+minNum);
}
}
Answer:
As you asked that you just wanted to remove the decimal places for that you need to create new int value and type cast the output value with decimal places into the integer by doing that it will remove the values after the decimal point.
But using Math.round() is not encouraged because it will convert the value to nearly round value like if the values in 99.99 it will gives you the output 100 but we only need 99 and .99 should be removed to get that we need to create a new int value
Here is the modification of you code to meet your requirement:
Raw code:
import java.util.Scanner;
import java.lang.Math;
public class Main {
public static void main(String[] args) {
double numbers[] = new double[5];
inputArray(numbers);
maxNumber(numbers);
minNumber(numbers);
}
public static void inputArray( double[] numbers) {
Scanner in = new Scanner(System.in);
for(int i = 0; i < numbers.length; i++) {
numbers[i] = in.nextDouble();
}
}
public static void maxNumber(double[] numbers) {
double maxNum = numbers[0];
for(int i = 0; i < numbers.length; i++) {
if(numbers[i] > maxNum ) {
maxNum = numbers[i];
}
}
//creating new int value with type casting
int maxValue= (int)maxNum;
System.out.println("Max: "+maxValue);
}
public static void minNumber(double[] numbers) {
double minNum = numbers[0];
for(int i = 0; i < numbers.length; i++) {
if(numbers[i] < minNum ) {
minNum = numbers[i];
}
}
//creating new int value with type casting
int minValue=(int)minNum;
System.out.println("Min: "+minValue);
}
}
Code in the editor:
output:
Hope this helps you! If you still have any doubts or queries please feel free to comment in the comment section.
"Please refer to the screenshot of the code to understand the indentation of the code".
Thank you! Do upvote.