Write a java program that receives two values from the user, adds them together and
display the answer.
1.first option. display sum of two numbers
import java.math.BigDecimal;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the first number: ");
String first = sc.nextLine();
System.out.print("Enter the second number: ");
String second = sc.nextLine();
//check inputs format (only digits and digits with floating point. positive and negative)
if(!first.matches("[-]?\\d+([.]\\d+)?") || !second.matches("[-]?\\d+([.]\\d+)?")) {
System.out.println("Wrong input format");
} else {
BigDecimal firstDecimal = BigDecimal.valueOf(Double.parseDouble(first));
BigDecimal secondDecimal = BigDecimal.valueOf(Double.parseDouble(second));
System.out.println("Answer: " + firstDecimal.add(secondDecimal));
}
sc.close();
}
}
2.second option. concat two string values and display it
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the first value: ");
String first = sc.nextLine();
System.out.print("Enter the second value: ");
String second = sc.nextLine();
System.out.println(first + second);
sc.close();
}
}
Comments
Leave a comment