Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package week3training;
- import java.util.Scanner;
- public class Day16A {
- public static void main(String[] args) {
- Scanner sc = new Scanner(System.in);
- double num1;
- try {
- System.out.print("Enter number: ");
- num1 = sc.nextDouble();
- System.out.println("... Computing");
- } catch (Exception e) {
- System.out.println("You entered an invalid number.");
- System.out.println("Number will default to 1");
- num1 = 1;
- }
- num1 /= 2;
- System.out.println("Half of number: " + num1);
- }
- }
- //-------------------
- public static void main(String[] args) {
- Scanner sc = new Scanner(System.in);
- int arrIndex = 0;
- int[] numArray = new int[5];
- try {
- System.out.print("Enter Array Index: ");
- arrIndex = sc.nextInt();
- System.out.print("Enter value of cell: ");
- numArray[arrIndex] = sc.nextInt();
- } catch (ArrayIndexOutOfBoundsException e) {
- System.out.println("Array index more than array size");
- } catch (Exception e) {
- System.out.println("There is an error");
- }
- for (int i = 0; i < numArray.length; i++) {
- System.out.println(i + " : " + numArray[i]);
- }
- }
- //-----------------------------------------
- package week3training;
- import java.util.Scanner;
- public class Day16C {
- public static void main(String[] args) {
- Scanner sc = new Scanner(System.in);
- double num1=0, num2=0;
- String op, userInput;
- System.out.print("Enter number 1: ");
- userInput = sc.nextLine();
- if (isNumeric(userInput)) {
- num1 = Double.parseDouble(userInput);
- userInput = "";
- }
- System.out.print("Enter operator(+,-,*,/): ");
- op = sc.nextLine();
- System.out.print("Enter number 2: ");
- userInput = sc.nextLine();
- if (isNumeric(userInput)) {
- num2 = Double.parseDouble(userInput);
- userInput = "";
- }
- // calling compute method to do the calculate result
- compute(num1, num2, op);
- }
- public static boolean isNumeric(String strNum) {
- if (strNum == null) {
- return false;
- }
- try {
- double d = Double.parseDouble(strNum);
- } catch (NumberFormatException nfe) {
- return false;
- }
- return true;
- }
- public static void compute(double num1, double num2, String operator) {
- double result = 0;
- boolean validOp = true;
- switch (operator) {
- case "+":
- result = num1 + num2;
- break;
- case "-":
- result = num1 - num2;
- break;
- case "*":
- result = num1 * num2;
- break;
- case "/":
- result = num1 / num2;
- break;
- default:
- validOp = false;
- }
- if (validOp)
- System.out.println(num1 + operator + num2 + "=" + result);
- else
- System.out.println("Operator not valid");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement