【问题标题】:Using enum with a switch case String for my assignment将枚举与 switch case 字符串一起用于我的分配
【发布时间】:2021-10-09 23:48:08
【问题描述】:

我已经对代码进行了更改,并且能够成功我希望将 switch case 与字符串一起使用。现在我只需要帮助为字符串 getDirection 声明两个变量。我需要将其声明为“右”和“左”

String quit= "exit";
  String choice;
  String getDirection= "Right";//I need it to be declared as both left and right
  
  quit.equalsIgnoreCase("exit");
  
do
{
  System.out.println("would you like the bug to move or turn around?");
  System.out.println();
  System.out.println("Or enter 'exit' to quit");
  choice= scan.nextLine();
  
  option options=option.MOVE;
  
  switch(options)
  {
      case MOVE:
          b.move();
          if (getDirection.equals("Right"))
              System.out.println("The bug moved 1 unit towards " + b.getDirection("Right ") + " and is now at position " + b.getPosition());
              else if (getDirection.equals("Left"))
              System.out.println("The bug moved 1 unit towards " + b.getDirection("Left ") + " and is now at position " + b.getPosition());
          
           

【问题讨论】:

  • 将枚举值命名为大写是标准做法,如MOVETURN
  • 而且,通常最好用单数而不是复数来命名枚举类。
  • 谢谢,我已经更正了@chrylis-cautiouslyoptimistic-
  • 这不可能是真的:if (d.equals("Right") & d.equals("Left"))
  • 这里的字符串参数没有用:public String getDirection(String dir)//gives the direction the bug is faced

标签: java string enums switch-statement


【解决方案1】:
  if (b.getDirection.equals("Right"))//this getDirection is showing up as an error

那是因为 Bug 类中没有名为 getDirection 的成员变量。

您已经定义了一个名为 getDirection 的局部变量,它与 Bug 类无关。

您可能打算调用 b.getDirection() 方法,类似于您在同一段代码中的类似调用。

顺便说一句,IMO 变量应该有名称的名词短语,而不是动词短语。所以,方法 getDirection() 是名副其实的,变量 getDirection 不是。

【讨论】:

  • 使用方法 b.getDirection().equals("Right") 时仍然收到错误消息
  • 确切的错误是什么?并请发布类 Bug 的来源。否则我们只能猜测它的样子。
  • 我已经添加了 Bug 类并且相信我已经成功地使用了 case 开关,但是现在我需要帮助来为 String getDirection 声明两个变量。我需要它同时是“左”和“右”。现在我的输出破折号 (-) 是垂直的,有没有办法让它们与 (X) 一起水平显示?
  • 我不知道String getDirection= "Right";//I need it to be declared as both left and right 中的评论是什么意思。这个变量的使用决定了错误的移动方式。它不能同时左右移动。您将此选择硬连线到程序中似乎很奇怪,但我认为这只是“仍在开发中的程序”。然而,对于任何一个 MOVE,它必须是左右,而不是两者。
  • 如何声明它以使其向右或向左移动?因为现在它唯一的向右移动
猜你喜欢
  • 2021-12-17
  • 2020-12-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-16
  • 1970-01-01
相关资源
最近更新 更多