tziroldo
tziroldo

Reputation: 1

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

  }
}

Upvotes: 0

Views: 2619

Answers (2)

talex
talex

Reputation: 20544

Use this code

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

Upvotes: 1

codemirel
codemirel

Reputation: 160

You do not have to extract anything, just convert the String input to Double and apply Math.Abs on it, which is the built-in absolute value method. (https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html)

Check this out:

Scanner input = new Scanner(System.in);
double num = Double.parseDouble(in.next());
System.out.println(Math.abs(num));

Upvotes: 0

Related Questions