如何使字符串等于扫描程序和“ if”语句?

时间:2018-09-20 02:34:31

标签: java java.util.scanner

让用户在控制台中输入字符串并且他们键入的特定字符串等于if语句时,我遇到了很多麻烦。我想在控制台中输入“ SquareRoot”,然后转到if语句,但是当我键入它时,什么也没发生。我该怎么做才能解决此问题?如何使用户输入等于字符串和if语句?我的“ if”语句出问题了吗?

Scanner userInput = new Scanner(System.in);

String SquareRoot;

System.out.println("Type 'SquareRoot' - find the square root of (x)")
SquareRoot = userInput.next();

if(SquareRoot.equals("SquareRoot")) {

    Scanner numInput = new Scanner(System.in);
    System.out.println("Enter a number - ");
    double sR;
    sR = numInput.nextDouble();
    System.out.println("The square root of " + sr + "is " + Math.sqrt(sR));

1 个答案:

答案 0 :(得分:0)

您的代码基本上是正确的:

  • 您有一些错字,可能会阻止代码成功编译。您 应该考虑使用诸如Eclipse之类的IDE,因为它将突出显示这些内容。 键入时会遇到各种问题。

  • 您不应创建第二个Scanner对象,而应重复使用现有的对象。

  • 完成后请确保关闭扫描仪

这是您的更正代码:

  public static void main(String[] args)
  {
    Scanner userInput = new Scanner(System.in);

    String SquareRoot;

    System.out.println("Type 'SquareRoot' - find the square root of (x)");
    SquareRoot = userInput.next();

    if (SquareRoot.equals("SquareRoot"))
    {
      // You shouldn't create a new Scanner
      // Scanner numInput = new Scanner(System.in);
      System.out.println("Enter a number - ");
      double sR;
      // Reuse the userInput Scanner
      sR = userInput.nextDouble();
      System.out.println("The square root of " + sR + " is " + Math.sqrt(sR));
    }

    // Be sure to close your Scanner when done
    userInput.close();
  }