【问题标题】:Validating for Java; only two string characters allowed验证Java;只允许两个字符串字符
【发布时间】:2016-10-10 18:02:10
【问题描述】:

我正在尝试验证应该只接受 customerType 作为 RC 的输入。它不区分大小写。我的代码出错,它说我的String customerType 丢失:

import java.text.NumberFormat;
import java.util.InputMismatchException;
import java.util.Scanner;

public class InvoiceApp
{
  public static void main(String[] args)
  {
    // Begin input
    Scanner sc = new Scanner(System.in);
    String choice = "y";

    while (!choice.equalsIgnoreCase("n"))
    {
      // get the input from the user
      // create catch block for customerType(r or c)
      try
      {
        System.out.print("Enter customer type (r/c): ");
        String customerType = sc.next();
      }
      catch (InputMismatchException e)
      {
        if (customerType != "r" || "c")
        {
          sc.next();
          System.out.println("Enter a valid customer type r or c");
          continue;
        }
        else
        {
          System.out.print("Enter subtotal:   ");
        }
      }
      double subtotal = sc.nextDouble();
      // get the discount percent
      double discountPercent = 0;
      if (customerType.equalsIgnoreCase("R"))
      {
        if (subtotal < 100)
          discountPercent = 0;
        else if (subtotal >= 100 && subtotal < 250)
          discountPercent = .1;
        else if (subtotal >= 250)
          discountPercent = .2;
      }
      else if (customerType.equalsIgnoreCase("C"))
      {
        if (subtotal < 250)
          discountPercent = .2;
        else
          discountPercent = .3;
      }
      else
      {
        discountPercent = .1;
      }

      // calculate the discount amount and total
      double discountAmount = subtotal * discountPercent;
      double total = subtotal - discountAmount;

      // format and display the results
      NumberFormat currency = NumberFormat.getCurrencyInstance();
      NumberFormat percent = NumberFormat.getPercentInstance();
      System.out.println("Discount percent: " + percent.format(discountPercent)
          + "\n" + "Discount amount:  " + currency.format(discountAmount) + "\n"
          + "Total:            " + currency.format(total) + "\n");

      // see if the user wants to continue
      System.out.print("Continue? (y/n): ");
      choice = sc.next();
      System.out.println();
    }
  }
}

【问题讨论】:

  • 您已将声明 String customerType 放入您的 try 中,因此它仅在 try 中具有范围。在你的try 之前声明String customerType;,然后在你的try 中使用customerType = sc.next();
  • 也不要使用==!= 来比较Strings:customerType != "r" || "c"。使用.equals().equalsIgnoreCase()...
  • 并且必须在运算符的两侧进行比较。它应该是这样的:( !customerType.equalsIgnoreCase("r") || !customerType.equalsIgnoreCase("c") )
  • next() 实际上cannot throw InputMismatchException,但即使可以,异常也意味着customerType = sc.next() 执行失败,这意味着没有读取任何内容来自输入,因此尝试在 catch 块中验证 customerType 是完全没有意义的,即使您确实获得了要编译的代码。 --- 好奇:是什么让你认为你需要在这样的 catch 子句中编写所有代码?

标签: java validation


【解决方案1】:

首先,您的错误的原因是 customerType 字符串的范围仅限于声明它的 try 块。由于无法在 try 块之外(在您的情况下,在 catch 块内)访问它,因此编译器会生成错误。

而且您不需要将代码放在 try/catch 块中,因为没有可以生成异常的代码。

要解决这个问题,可以有不止一种方法:

  1. 在 try 块之外声明 customerType 字符串,并将其初始化为 null 或空字符串。

  2. 第二种方式(如果需要 try/catch 块,我会更喜欢)是移动所有 try 块中的逻辑。这样您就不必在 try 块之外声明它,并且所有使用 customerType 的代码都将保持干净(没有任何错误),因此您不必担心错误。并且,还包括在 catch 块内发生上述异常时要执行的代码。您的 catch 块应仅包含仅在发生异常时才运行的代码。

这些建议与您的代码问题有关。

  1. 由于不需要 try/catch 块,因此删除这些块并将您的代码放在它们之外的 main 将单独工作。

您的代码的另一个问题是您在 if 语句中输入了错误的条件。正确的做法是:

if (customerType.equals("r") || customerType.equals("c")){
                ...
            }

除此之外,您还需要在使用 discountPercent 之前声明 discountPercent(您没有)并初始化为 0。

无论如何,这是带有更正代码的主要方法(其余行将与您的相同)。

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    String choice = "y";

    while (!choice.equalsIgnoreCase("n")){
        System.out.print("Enter customer type (r/c): ");
        String customerType = sc.next();
        if (customerType.equalsIgnoreCase("r")||customerType.equalsIgnoreCase("c")){
            sc.next();
            System.out.println("Enter a valid customer type r or c");
            continue;
        }
        else{
            System.out.print("Enter subtotal:   ");
        }
        double subtotal = sc.nextDouble();
        double discountPercent = 0;
        if (customerType.equalsIgnoreCase("R")){
            if (subtotal < 100)
                discountPercent = 0;
            else if (subtotal >= 100 && subtotal < 250)
                discountPercent = .1;
            else if (subtotal >= 250)
                discountPercent = .2;
        }
        else if (customerType.equalsIgnoreCase("C")){
            if (subtotal < 250)
                discountPercent = .2;
            else
                discountPercent = .3;
        }
        else{
            discountPercent = .1;
        }

        // calculate the discount amount and total
        double discountAmount = subtotal * discountPercent;
        double total = subtotal - discountAmount;

        // format and display the results
        NumberFormat currency = NumberFormat.getCurrencyInstance();
        NumberFormat percent = NumberFormat.getPercentInstance();
        System.out.println(
                "Discount percent: " + percent.format(discountPercent)
       + "\n" +
                "Discount amount:  " + currency.format(discountAmount) 
       + "\n" +
                "Total:            " + currency.format(total) + "\n");

        // see if the user wants to continue
        System.out.print("Continue? (y/n): ");
        choice = sc.next();
        System.out.println();
    }
}

如果您还有任何疑问,请告诉我。我很乐意为您提供帮助。

编辑 1:

根据@Andreas 的建议,我已经更正了我输入错误的条件语句。

【讨论】:

【解决方案2】:

这可行,但如果您在不更新总销售额的情况下循环提示客户继续提示,则毫无意义。

import java.text.NumberFormat;
import java.util.Scanner;

public class InvoiceApp
{
  public static void main(String[] args)
  {
    // Begin input
    Scanner sc = new Scanner(System.in);
    String customerType = null;
    boolean choice = true;
    while (choice)
    {
      // get the input from the user
      System.out.print("Enter customer type (r/c): ");
      customerType = sc.next();
      while (!customerType.equalsIgnoreCase("r")
          && !customerType.equalsIgnoreCase("c"))
      {
        System.out.println("Enter a valid customer type r or c");
        customerType = sc.next();
      }

      System.out.print("Enter subtotal:   ");

      double subtotal = sc.nextDouble();
      // get the discount percent
      double discountPercent = 0;
      if (customerType.equalsIgnoreCase("R"))
      {
        if (subtotal < 100)
          discountPercent = 0;
        else if (subtotal >= 100 && subtotal < 250)
          discountPercent = .1;
        else if (subtotal >= 250)
          discountPercent = .2;
      }
      else if (customerType.equalsIgnoreCase("C"))
      {
        if (subtotal < 250)
          discountPercent = .2;
        else
          discountPercent = .3;
      }
      else
      {
        discountPercent = .1;
      }

      // calculate the discount amount and total
      double discountAmount = subtotal * discountPercent;
      double total = subtotal - discountAmount;

      // format and display the results
      NumberFormat currency = NumberFormat.getCurrencyInstance();
      NumberFormat percent = NumberFormat.getPercentInstance();
      System.out.println("Discount percent: " + percent.format(discountPercent)
          + "\n" + "Discount amount:  " + currency.format(discountAmount) + "\n"
          + "Total:            " + currency.format(total) + "\n");

      // see if the user wants to continue
      System.out.print("Continue? (y/n): ");
      String userInput = sc.next();
      choice = userInput.equalsIgnoreCase("y");
      System.out.println();
    }
    sc.close();
  }
}

【讨论】:

  • 不客气,如果您当时接受我的回答是正确的,我将不胜感激!要接受答案,请选择一个您认为是解决问题的最佳方法的答案。要将答案标记为已接受,请单击答案旁边的复选标记以将其从灰色切换为已填充。
猜你喜欢
  • 2019-07-16
  • 1970-01-01
  • 2020-02-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多