2013-04-18 34 views
-1
public static String getSubMenu(String submenu){ 
     Scanner keyboard = new Scanner(System.in); 
     String chosen="", A="A",B="B", a="a", b="b"; 
     do{ 
     chosen = keyboard.next(); 
     keyboard.nextLine(); 
     System.out.print("\n\n"); 
     }while(chosen.compareTo(A)); 
     return chosen; 
    } 
    //This function below is fine. 
    public static void Menu(){ 
     String unem=""; 
     do{ 
     System.out.println("Sub Menu"); 
     System.out.println("Select an Option\n\n"); 
     System.out.println("a.Sort by name\n" +        
          "b.Sort by time\n" + 
          "c.Exit sub-menu\n\n"); 
     System.out.print("Input the number for the selected option: "); 
     unem= getSubMenu(unem); 
     if("a".equals(unem)|| "A".equals(unem)){ 

     } 
     if("b".equals(unem)|| "B".equals(unem)){ 

     } 
    }while ("a".equals(unem) ||"b".equals(unem) || "A".equals(unem) || "B".equals(unem)); 

    } 

} 

嗨,我想做一个子菜单。正如您在功能Menu中看到的那样,当调用getSubMenu时,用户必须在函数getSubMenu中输入选定的选项。我通过看教材和在线和它似乎没有,你可以争论中使用char使用String/char创建子菜单?

char a="a"; 
if(a != b); 

如果您可以使用字符,而不是字符串上述功能,请告诉我们。

但继续前进。我现在想要做的是让getSubMenu返回一个包含'A' || 'a' || 'b' || 'B' || 'c' || 'C'的字符串,然后在用户没有将其中的任何一个作为输入时循环。我试过尝试使用compareTo,但我收到Type mismatch: cannot convert from int to boolean error我该如何改进。我可以使用什么语法,以便这可以工作。

感谢大家的帮助和贡献。

编辑:新的工作职能

public static String getSubMenu(String submenu){ 
      Scanner keyboard = new Scanner(System.in); 
      boolean looped = true; 
      String chosen=""; 
      do{ 
      chosen = keyboard.next(); 
      keyboard.nextLine(); 
      System.out.print("\n\n"); 
      if("a".equals(option)|| "A".equals(option) || "b".equals(option)|| "B".equals(option) || "c".equals(option)|| "C".equals(option)){ 
       looped = false; 
      } 
      else 
       System.out.println("Wrong input"); 
      }while(looped); 
      return option; 

可能的没有什么,我瞄准了,但它仍然做到了工作。

+0

它应该是'char a ='a'',单引号! – NINCOMPOOP 2013-04-18 04:12:38

+0

啊我的不好:(对不起 – Daxter 2013-04-18 04:25:01

回答

1

while(chosen.compareTo(A))是你应该得到一个错误的地方。方法compareTo(String)返回int,您不能在while(boolean expression)中使用它,它需要一个布尔表达式,其值应为truefalse。我粘贴用于参考的代码,凑合它:

public static String getSubMenu(String submenu) { 
    Scanner keyboard = new Scanner(System.in); 
    List<String> list = Arrays.asList(new String[]{"A","B","C"}); 
    do { 
     chosen = keyboard.next(); 
     keyboard.nextLine(); 
     System.out.print("\n\n"); 
    } while (chosen!=null && list.contains(chosen.toUpperCase())); 
    return chosen; 
} 
+0

感谢,更有意义所以我可以看到为什么循环由于错误的变量而不能正常工作。 – Daxter 2013-04-18 04:24:39

0

compareTo()比较2个对象,并返回表示该对象是大于一个int。由于它不是布尔值,因此do while循环无法编译。如果您正在寻找来自用户的特定输入,请使用此代码段。

 do 
     { 
      chosen = keyboard.next(); 
      keyboard.nextLine(); 
      System.out.print("\n\n"); 
     } 
     while (!chosen.trim().equalsIgnoreCase("a")); 

你需要trim()字符串删除空格一样的字符,你可以使用equalsIgnoreCase()匹配“A”和“A”。