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

时间:2015-10-05 01:52:18

标签: java if-statement java.util.scanner add tax

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

  }
 }

2 个答案:

答案 0 :(得分: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))); 

答案 1 :(得分:0)

您只需要一个Scanner。您可以在else测试中使用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);
}