【问题标题】:How to make a string equal a scanner and "if" statement?如何使字符串等于扫描仪和“if”语句?
【发布时间】:2018-09-20 02:34:30
【问题描述】:

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

【问题讨论】:

  • squareRoot = userInput.nextLine();SquareRoot 看起来像一个类名)。
  • Scanner userInput = new Scanner - 看起来不正确,可能只是错字?
  • 是的,很抱歉这是一个错字。我修好了:)
  • 另外,你不需要实例化一个新的Scanner对象,只需重复使用userInput
  • 显示的代码后面是什么?它应该类似于} else { System.out.println("Invalid input: " + SquareRoot ); },因此用户可以看到程序检测到他们输入的内容。

标签: java java.util.scanner


【解决方案1】:

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

  • 您有一些拼写错误会阻止您的代码编译成功。你 应该考虑使用 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();
  }

【讨论】:

  • 完成后一定要关闭你的扫描仪而不是System.in输入流,
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多