2012-08-01 46 views
0

我有一個菜單驅動的程序,用戶被提示輸入可能的整數,因爲他們想要建立一個二叉搜索樹 - 我剛剛開始並且卡住了失控的閱讀他們的整數一旦他們打「Q」當從用戶輸入掃描整數時使用char哨兵

switch(inputOption){ 
     case 1: 
      System.out.println("You've selected to create a new binary tree." + "\n"); 
      Scanner scan = new Scanner(System.in); 
      String again; 
      String tempInput; 
      Boolean repeat = true; 
      try{ 
       System.out.println("Please enter as many integers as you'd like, hit 'Q' when you are finished." + "\n"); 
       do{ 

        tempInput = scan.next(); 
        if(tempInput != "Q"){ 
         integerInput = Integer.parseInt(tempInput); 
         repeat = true; 
        } 
        else 
         repeat = false; 

       }while(repeat); 
      }catch(InputMismatchException e){} 

我如何能得到它認識到「Q」任何想法?

回答

1

使用

if(!tempInput.equals("Q")) 

而不是

if(tempInput != "Q") 

Java字符串不與比較運營商合作。

+0

不錯,忘了那個。這也總是讓我感到... – 2012-08-01 22:07:55

+1

啊啊是的 - 在鑽入C++後很難讓C++失去它的大腦! – 2012-08-01 22:11:51

+0

告訴我關於它的事情:) – ryanbwork 2012-08-01 22:14:59

0

嘗試添加(||「q」)可能可能有所幫助。儘管你並沒有提供太多的信息。例如你是否使用調試器來分析tempInput的實際值以確定它實際上是「Q」?如果是這樣,那麼可以嘗試轉換爲字符,或者修剪任何可能包含的額外空白或特殊字符。

更多信息將會更好:-D