2013-04-06 80 views
0
public static void main(String[] args) {  
    Scanner in = new Scanner(System.in); 
    System.out.print("Please choose.('e' to encrypt, 'd' to decrypt, 'q' to quit): "); 
    String userIn= in.next(); 
    if(userIn.equals("e")){ 
     System.out.println("Please enter your text that you want to encrypt: "); 
     String userInput = in.nextLine(); 

     System.out.print("Please enter your shift key(0-25): "); 
     int userS = in.nextInt(); 
     if(userS < 0 || userS > 25){ 
      System.out.print("Invalid shift key, please enter a valid shift key: "); 
      userS = in.nextInt(); 
     } 

在我上面的程序:在汽車後面的代碼部分跳過輸入

System.out.println("Please enter your text that you want to encrypt: "); 
       String userInput = in.nextLine(); 

       System.out.print("Please enter your shift key(0-25): "); 

它跳過此userInput,它越過它,並要求shift鍵之前,我輸入的文本。

回答

1

這個固定(在Eclipse測試):

Scanner in = new Scanner(System.in); 
System.out.print("Please choose.('e' to encrypt, 'd' to decrypt, 'q' to quit): "); 
String userInput = in.nextLine(); 
if (userInput.equals("e")) 
{ 
    System.out.println("Please enter your text that you want to encrypt: "); 
    userInput = in.nextLine(); 

    System.out.print("Please enter your shift key(0-25): "); 
    int userS = Integer.parseInt(in.nextLine()); 
    if (userS < 0 || userS > 25) 
    { 
     System.out.print("Invalid shift key, please enter a valid shift key: "); 
     userS = Integer.parseInt(in.nextLine()); 
    } 
} 
in.close(); 

我改變了你的userIn變量只是userInput,因爲我們沒不需要它;您的next()電話也被更改爲nextLine()

我也將您所有的nextInt()的更改爲nextLine()的。這將幫助您稍後避免Exception

最後,當您完成保存系統資源時,請始終關閉Scanner

0

變化:

String userInput = in.nextLine() 

in.nextLine(); String userInput = in.nextLine(); 
0

簡單,你的代碼更改爲

String userInput = in.next(); 
+1

如果你這樣做,那麼你不能進入一個句子。你只能輸入一個單詞。 – user2059140 2013-04-06 19:53:20