2015-10-05 102 views
0

嗨我需要幫助在這裏進行計算。在它有單個的行上,我想將該數字添加到計算中,但它只是添加它,就好像我只是在句子中寫入數字本身一樣。我如何將它添加,如果它的計算,我很困難,需要幫助。 (它是最後一行代碼)。我也想知道如何限制用戶可以輸入的字母數量,因爲我只希望他們輸入's'或'm'。我怎樣才能限制他們只有這兩個,所以他們不使用像'g'這樣的字母,因爲這不會工作。如何在字符串中添加一個整數,java並限制用戶輸入

import java.util.Scanner; 
public class FedTaxRate 
{ 
public static void main(String[] args) 
{ 
    String maritalStatus; 
    double income; 
    int single = 32000; 
    int married = 64000; 

    Scanner status = new Scanner(System.in); 
    System.out.println ("Please enter your marital status: "); 
    maritalStatus = status.next(); 


    Scanner amount = new Scanner(System.in); 
    System.out.print ("Please enter your income: "); 
    income = amount.nextDouble(); 

    if (maritalStatus.equals("s") && income <= 32000) 
    { 
    System.out.println ("The tax is " + income * 0.10 + "."); 
    } 
    else if (maritalStatus.equals("s") && income > 32000) 
    { 
    System.out.println ("The tax is " + (income - 32000) * 0.25 + single + "."); 
    } 

    } 
} 
+0

使用括號,'的System.out.println( 「稅收是」 +(收入×0.10)+ 「」)' – MadProgrammer

+0

在該行的產品是正確的IM問到這個問題之一: (「s」)&&收入> 32000) System.out.println(「Tax is」+(income - 32000)* 0.25 + single +「。」); } – McDodger

+0

同樣的事情,用括號包裹整個計算 – MadProgrammer

回答

1

要回答關於限制輸入的第二個問題,您可以嘗試使用switch case語句。 default允許您爲maritalStatus不等於"s""m"的情況編寫代碼。您也可以創建一個do-while循環來繼續詢問輸入,直到maritalStatus等於"s""m"

Scanner status = new Scanner(System.in); 
String maritalStatus = status.nextLine(); 

do { 
    System.out.println("Enter your marital status.") 
    switch (maritalStatus) { 
     case "s": 
      // your code here 
      break; 
     case "m": 
      // your code here 
      break; 
     default: 
      // here you specify what happens when maritalStatus is not "s" or "m" 
      System.out.println("Try again."); 
      break; 
     } 
    // loop while maritalStatus is not equal to "s" or "m" 
    } while (!("s".equalsIgnoreCase(maritalStatus)) && 
      !("m".equalsIgnoreCase(maritalStatus))); 
0

您只需要一個Scanner。您可以在income測試中使用else。我建議你計算tax一次,然後用格式化的IO顯示它。類似的,

public static void main(String[] args) { 
    int single = 32000; 
    int married = 64000; 
    Scanner sc = new Scanner(System.in); 
    System.out.println("Please enter your marital status: "); 
    String maritalStatus = sc.next(); 

    System.out.print("Please enter your income: "); 
    double income = sc.nextDouble(); 
    double tax; 
    if ("s".equalsIgnoreCase(maritalStatus)) { 
     if (income <= single) { 
      tax = income * 0.10; 
     } else { 
      tax = (income - single) * 0.25 + single; 
     } 
    } else { 
     if (income <= married) { 
      tax = income * 0.10; 
     } else { 
      tax = (income - married) * 0.25 + married; 
     } 
    } 
    System.out.printf("The tax is %.2f.%n", tax); 
} 
相關問題