Write a program to take a String which is in decimal form as input then display how many int values were found, how many decimal values were found. Then display the integer part and decimal part separately and their addition with appropriate heading.
Hint: Use java.io package and parseInt()
import java.util.Scanner;
class App {
public static void main(String[] args) {
java.util.Locale.setDefault(new java.util.Locale("en-US", "en-US"));
Scanner keyBoard = new Scanner(System.in);
System.out.print("Ente a String: ");
String[] numbersStr = keyBoard.nextLine().split(" ");
int intValuesCounter = 0;
double decimalValuesCounter = 0;
double sum = 0;
for (int i = 0; i < numbersStr.length; i++) {
if (numbersStr[i].contains(".")) {
try {
double doubleValue = Double.parseDouble(numbersStr[i]);
sum += doubleValue;
System.out.println("Double value: " + doubleValue);
decimalValuesCounter++;
} catch (Exception e) {
System.out.println("Wrong value");
}
} else {
try {
int intValue = Integer.parseInt(numbersStr[i]);
sum += intValue;
System.out.println("Integer value: " + intValue);
intValuesCounter++;
} catch (Exception e) {
System.out.println("Wrong value");
}
}
}
System.out.println(intValuesCounter + " int values were found");
System.out.println(decimalValuesCounter + " decimal values were found");
System.out.println("Sum: " + sum);
keyBoard.close();
}
}
Comments
Leave a comment