首页 > 解决方案 > 如何使字符串等于扫描仪和“if”语句?

问题描述

让用户在控制台中输入字符串并且他们输入的特定字符串等于 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));

标签: javajava.util.scanner

解决方案


您的代码大部分是正确的:

  • 您有一些拼写错误会阻止您的代码成功编译。您应该考虑使用 IDE,例如 Eclipse,因为它会在您键入时为您突出显示这些类型的问题。

  • 您不应该创建第二个 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();
  }

推荐阅读