Answer to Question #265008 in Java | JSP | JSF for Penda

Question #265008

Write a java program that receives two values from the user, adds them together and


display the answer.

1
Expert's answer
2021-11-12T16:32:18-0500

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();
    }
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS