[Solved] How to make a string equal a scanner and “if” statement?


Your code was mostly correct:

  • You had some typos that would prevent your code compiling successfully. You
    should consider using an IDE such as Eclipse, as it will highlight these
    kinds of issues for you as you type.

  • You shouldn’t create a 2nd Scanner object, reuse the existing one

  • Be sure to close your Scanner when done

Here’s your corrected code:

  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();
  }

1

solved How to make a string equal a scanner and “if” statement?