java - 尝试让用户输入正常工作

标签 java recursion user-input towers-of-hanoi

我有一个汉诺塔谜题程序,即将完成。我现在的问题是试图让用户的输入正常工作。

如果他们输入“v”或“V”,则会显示解决难题的步骤(因此输出将是“将光盘从 S 移动到 D”等等)。否则,如果用户不输入“v”或“V”,则程序将继续解决谜题,显示总移动数,但不显示步数。

我遇到的问题是选项没有像预期的那样工作。

现在唯一的问题是当用户输入“v”或“V”时, Action 显示不正确。 输出:

Enter the min number of discs : 
2
Press 'v' or 'V' for a list of moves
v
 Move disc from needle S to A
 Total Moves : 3

如果用户键入“v”或“V”,并且如果用户键入除此之外的其他内容,则输出仅显示“总移动”,如何实现显示移动?

这是我的代码:

 import java.util.*;

import java.util.Scanner;

public class TowerOfHanoi4 {
   static int moves=0;
   public static void main(String[] args) {

   System.out.println("Enter the min number of discs : ");
        Scanner scanner = new Scanner(System.in);
        int iHtMn = scanner.nextInt();       //iHeightMin         

        char source='S', auxiliary='D', destination='A';       //name poles or 'Needles'

   System.out.println("Press 'v' or 'V' for a list of moves");     
        Scanner show = new Scanner(System.in);
        String c = show.next();
        // char lstep='v', lsteps='V';       // grab option v or V

   if (c.equalsIgnoreCase("v")){        //if option is not v or V, execute code and only display total moves
    hanoi(iHtMn, source, destination, auxiliary); //else, user typed v or V and moves are displayed
    System.out.println(" Move disc from needle "+source+" to "+destination);
    System.out.println(" Total Moves : "+moves);
   } else {
      hanoi(iHtMn, source, destination, auxiliary);
      System.out.println(" Total Moves : "+moves);
     }  
   }


    static void hanoi(int htmn,char  source,char  destination,char  auxiliary)
      {
      if (htmn >=1)
          {
             hanoi(htmn-1, source, auxiliary, destination); // move n-1 disks from source to auxilary
              // System.out.println(" Move disc from needle "+source+" to "+destination); // move nth disk to destination
             moves++;     
             hanoi(htmn-1, auxiliary, destination, source);//move n-1 disks from auxiliary to Destination
          }
          // else (
      }
}

最佳答案

检查此行

if (c != lstep || c != lsteps){////}

即使 c 是 v 或 V,这也会起作用。 如果 c = 'v',则 c != 'V',因此此 'if 测试' 适用于 v 或 V。 将其更改为

if (c != lstep && c != lsteps){ 

关于java - 尝试让用户输入正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19803186/

相关文章:

c++ - 如何根据用户输入创建和访问多个对象 - C++

Python 正则表达式 : User Inputs Multiple Search Terms

java - 使用递归计算数组中负数的数量?

SVN不递归更新

java - 在 Java 中用于价格格式化的 DecimalFormat

java - 使用 Java 解码对象的 JSON 数组

c++ - 使用递归查找数组中的最大值

python - 如何使用 python 自动更改 html <input> 标签?

java - 检查日期列表是否包含特定日期

java - Groovy:DateUtil.format "yyyy-MM-dd"在格式化时递增一个月