如何使用字符串中给定的数字计算绝对值?

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

所以我正在编写一个程序,要求用户输入一个数字,然后 return 该数字的绝对值。我的程序应该允许 + 或 - 符号。 (or none) 以及带或不带小数点的数字。

由于我是初学者,所以我不想使用任何高级方法。

我写了一些我不确定我是否在正确轨道上的东西。 您可以在我的代码中看到我想如何计算绝对值。

我卡在哪里:如何提取字符串中给定的数字并使用该数字计算绝对值?

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

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

  }
}

你不需要提取任何东西,只需将String输入转换为Double并在其上应用Math.Abs,这是内置的绝对值方法。 (https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html)

看看这个:

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

使用此代码

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