0

嗨,我需要帮助来进行计算。在它有单个的行上,我想将数字添加到计算中,但它只是添加它,就好像我只是将数字本身写在一个句子中一样。我如何添加它,就好像它是一个计算一样,我非常卡住并且需要帮助。(它的最后一行代码)。我还想知道如何限制用户可以输入的字母数量,因为我只希望他们输入“s”或“m”。我怎样才能将它们限制为仅这两个,以便他们不使用例如“g”之类的字母,因为那不起作用。

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 + ".");
  }

  }
 }
4

2 回答 2

1

要回答关于限制输入的第二个问题,您可以尝试使用 switch case 语句。允许您为不等于或的default情况编写代码。您还可以创建一个 do-while 循环来不断询问输入,直到等于or 。maritalStatus"s""m"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))); 
于 2015-10-05T02:19:39.927 回答
0

你只需要一个Scanner。您可以将 anelse用于您的income测试。我建议你计算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);
}
于 2015-10-05T02:16:52.737 回答