2016-09-23 332 views
0

所以我正在寫一個程序,我要求用戶輸入一個數字,然後返回該數字的絕對值。我的程序應該允許+或 - 符號。 (或沒有)還有一個有或沒有小數點的數字。如何使用字符串中給出的數字來計算絕對值?

由於我是初學者,我不想使用任何高級方法。

我寫了一些東西,我不知道我是否在正確的軌道上。 你可以看到我想如何計算我的代碼中的絕對值。

我卡在哪裏:如何提取字符串中給出的數字並使用該數字計算abs值?

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

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

    } 
} 
+2

使用'Double.parse'然後'Math.abs' – talex

+0

如果你想使用字符串纔剛剛檢查那第一個simbol是'''',並通過'String.remove()' – talex

+0

刪除它是什麼意思。請舉例 – xxlali

回答

1

使用此代碼

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