jeudi 29 septembre 2016

Program won't run properly

So I wrote this program but for some reason my else statement won't work. If i input "e" for example my program will simply crash... when its actually supposed to return "Invalid Input" Can someone please help me?

=========================================================================

import java.util.Scanner;

public class AbsValue2 {
  public static void main(String[] args) {

  Scanner input = new Scanner(System.in);
  System.out.println("Enter a number:");
  String num = input.nextLine();
  Double num2 = new Double(Double.parseDouble(num));
  Double abs_val = new Double(Math.sqrt(num2 * num2));

  if (num.matches("[+-]?[\\d]+[.]*"))
    System.out.println("The absolute value of " + num + " is |" + abs_val + "|");
  else if (num.matches("[+-]?[\\d]*.[\\d]+"))
    System.out.println("The absolute value of " + num + " is |" + abs_val + "|");
  else
    System.out.println("Invalid input");

  }
}

Aucun commentaire:

Enregistrer un commentaire