如何在字符串中添加整数 java 并限制用户输入

How to add an integer in a string, java and limit user input

您好,我在这里需要帮助进行计算。在它只有一个的那一行,我想把这个数字加到计算中,但它只是把它加起来,就好像我只是把数字本身写在一个句子里一样。我如何添加它,就好像它是一个计算,我很卡住,需要帮助。 (它的最后一行代码)。我还想知道如何限制用户可以输入的字母数量,因为我只希望他们输入 '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 + ".");
  }

  }
 }

你只需要一个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);
}

要回答关于限制输入的第二个问题,您可以尝试使用 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)));