Search code examples
javaabsolute-value

How to use a number given in a string to calculate the absolute value?


So I am writing a program where I ask the user to enter a number and then I return the absolute value of that number. My program should allow + or - sign. (or none) And also a number with or without a decimal point.

Since I'm a beginner I don't want to use any advanced method.

I wrote something that I am not sure if I'm in the right track. You can see how I want to calculate the absolute value in my code.

Where I'm stuck: How do I extract the number given in a string and use that number to calculate the abs value?

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

import java.util.Scanner;

public class AValue {
  public static void main(String[] args) {
  Scanner input = new Scanner(System.in);
  System.out.println("Enter a number:");
  String num = input.nextLine();

  if (num.matches("[+-][\\d].[\\d]" ) )
    //calculation
    System.out.println("The absolute value ");
  else if (num.matches("[+-][\\d]" ) )
    //calculation
    System.out.println("The absolute value of " + num + " is ");
  else if (num.matches("[\\d]" ) )
    //calculation
    System.out.println("The absolute value of " + num + " is ");
  else if (num.matches("[\\d].[\\d]" ) )
    //calculation
    System.out.println("The absolute value of " + num + " is ");
  else
    System.out.println("Invalid number.");

  //x = x * x;
  //x = sqrt(x);

  }
}

Solution

  • Use this code

    Scanner input = new Scanner(System.in);
    double number = input.nextDouble();
    System.out.println(Math.abs(number));